package com.laowang.project.system.service.impl;

import java.io.IOException;
import java.math.BigDecimal;
import java.util.*;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.laowang.common.exception.CustomException;
import com.laowang.common.utils.*;
import com.laowang.common.utils.ip.IpUtils;
import com.laowang.framework.redis.RedisCache;
import com.laowang.framework.security.service.TokenService;
import com.laowang.framework.web.domain.AjaxResult;
import com.laowang.project.pay.config.*;
import com.laowang.project.system.controller.WxUserController;
import com.laowang.project.system.domain.*;
import com.laowang.project.system.domain.vo.OrderObject;
import com.laowang.project.system.domain.vo.PageObject;
import com.laowang.project.system.domain.vo.PayObject;
import com.laowang.project.system.mapper.MyCyhActivitySignMapper;
import com.laowang.project.system.mapper.MyCyhProProMapper;
import com.laowang.project.system.service.*;
import io.swagger.models.auth.In;
import lombok.extern.slf4j.Slf4j;
import netscape.javascript.JSObject;
import org.springframework.beans.factory.NoUniqueBeanDefinitionException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.annotation.QueryAnnotation;
import org.springframework.stereotype.Service;
import com.laowang.project.system.mapper.WxOrderMapper;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.PathVariable;
import oshi.jna.platform.mac.SystemB;


import javax.servlet.http.HttpServletRequest;
import javax.xml.crypto.Data;

/**
 * order对象Service业务层处理
 *
 * @author laowang
 * @date 2022-12-21
 */
@Slf4j
@Service
public class WxOrderServiceImpl implements WxOrderService {
    @Autowired
    private WxOrderMapper wxOrderMapper;


    @Autowired
    private IdWorker idWorker;

    @Autowired
    private RedisCache redisCache;

    @Autowired
    private WxUserService wxUserService;

    @Autowired
    private MyCyhShopService myCyhShopService;


    @Autowired
    private MyCyhMarkService myCyhMarkService;


    @Autowired
    private MyCarBookService myCarBookService;

    @Autowired
    private MyCyhActivitySignService myCyhActivitySignService;

    @Autowired
    private MyCyhActivityService myCyhActivityService;

    @Autowired
    private MyCyhVipService myCyhVipService;


    @Autowired
    private UserPointLogService userPointLogService;


    @Autowired
    private UserGoldLogService userGoldLogService;

    @Autowired
    private MyCyhTicketService myCyhTicketService;

    @Autowired
    private MyCouponService myCouponService;

    @Autowired
    private MyCyhShopCouponService myCyhShopCouponService;

    @Autowired
    private GZHPushMessageService gzhPushMessageService;

    @Autowired
    private MyGoodsBuyService myGoodsBuyService;

    @Autowired
    private MyGoodsService myGoodsService;

    @Autowired
    private MyFilesService myFilesService;

    @Autowired
    private MyCyhPositionService myCyhPositionService;

    @Autowired
    private MyCyhMerchantShareService myCyhMerchantShareService;

    @Autowired
    private MyCyhSerialNumberService myCyhSerialNumberService;

    @Autowired
    private MyCyhPartnerService myCyhPartnerService;


    @Autowired
    private MyCyhPartnerProService myCyhPartnerProService;


    @Autowired
    private MyCyhPartnerVipNumService myCyhPartnerVipNumService;


    @Autowired
    private MyCyhProVipNumService myCyhProVipNumService;


    @Autowired
    private MyCyhPromotionDorService myCyhPromotionDorService;

    @Autowired
    private MyCyhHolderService myCyhHolderService;

    @Autowired
    private MyCyhGladTidingService myCyhGladTidingService;

    @Autowired
    private MyCyhHolderVipNumService myCyhHolderVipNumService;

    @Autowired
    private MyCyhActivitySignMapper myCyhActivitySignMapper;

    @Autowired
    private WxOrderService wxOrderService;

    @Autowired
    private MyCyhRefundService myCyhRefundService;

    @Autowired
    private MyCyhShopCattleService myCyhShopCattleService;

    @Autowired
    private MyProductService myProductService;

    @Autowired
    private MyCyhShopProductService myCyhShopProductService;

    @Autowired
    private MyCyhParNowNumService myCyhParNowNumService;

    @Autowired
    private MyCyhProNowNumService myCyhProNowNumService;

    /**
     * 查询order对象
     *
     * @param id order对象ID
     * @return order对象
     */
    @Override
    public WxOrder selectWxOrderById(String id) {
        return wxOrderMapper.selectWxOrderById(id);
    }

    /**
     * 查询order对象列表
     *
     * @param wxOrder order对象
     * @return order对象
     */
    @Override
    public List<WxOrder> selectWxOrderList(WxOrder wxOrder) {
        return wxOrderMapper.selectWxOrderList(wxOrder);
    }

    /**
     * 新增order对象
     *
     * @param wxOrder order对象
     * @return 结果
     */
    @Override
    public int insertWxOrder(WxOrder wxOrder) {
        wxOrder.setCreateTime(DateUtils.getNowDate());
        return wxOrderMapper.insertWxOrder(wxOrder);
    }

    /**
     * 修改order对象
     *
     * @param wxOrder order对象
     * @return 结果
     */
    @Transactional
    @Override
    public int updateWxOrder(WxOrder wxOrder) {

        wxOrderMapper.updateWxOrder(wxOrder);

        return 1;
    }

    /**
     * 批量删除order对象
     *
     * @param ids 需要删除的order对象ID
     * @return 结果
     */
    @Override
    public int deleteWxOrderByIds(Long[] ids) {
        return wxOrderMapper.deleteWxOrderByIds(ids);
    }

    /**
     * 删除order对象信息
     *
     * @param id order对象ID
     * @return 结果
     */
    @Override
    public int deleteWxOrderById(Long id) {
        return wxOrderMapper.deleteWxOrderById(id);
    }

    /**
     *  股东奖励
     * @param wxUser
     * @param totalPrice
     * @param wxOrder
     * @param type 1 团队奖励  2直推会员奖励  ,3直推推荐官
     */
    public void gudongjiangli(WxUser wxUser,BigDecimal totalPrice,WxOrder wxOrder,Integer type){
        MyCyhHolder myCyhHolder = myCyhHolderService.selectMyCyhHolderById(1);
        if (myCyhHolder != null) {
            BigDecimal recommenVip = null;
            //11推荐官,12购买合伙人,13推荐官团队奖励,14合伙人团队奖励,15股东团队奖励
            String s1 = "";
            Integer typeMoney=null;
            if (type.equals(1)){
                recommenVip = myCyhHolder.getTeamReward();//团队奖励
                s1= "成员购买会员,股东获得团队奖励";
                typeMoney = 15;
            }else if (type.equals(2)){
                recommenVip = myCyhHolder.getRecommenVip();//直推会员奖励
                s1="分享购买会员,股东获得奖励";
                typeMoney = 4;
            } else if (type.equals(3)) {
                recommenVip = myCyhHolder.getPromo();//直推推荐官
                s1="分享购买推荐官,股东获得奖励";
                typeMoney = 11;
            }else if(type.equals(4)){
                recommenVip = myCyhHolder.getPartner();//直推合伙人
                s1="分享购买合伙人,股东获得奖励";
                typeMoney = 12;
            }else if (type.equals(5)){
                recommenVip = myCyhHolder.getTeamReward();//分享购买商家会员,股东获得团队奖励
                s1="分享购买商家会员,股东获得团队奖励";
                typeMoney = 15;
            }else if (type.equals(6)){
                recommenVip = myCyhHolder.getMerchant();//分享购买商家会员,股东获得奖励
                s1="分享购买商家会员,股东获得奖励";
                typeMoney = 5;
            }
             else {
                recommenVip = new BigDecimal(0);
            }

            Integer amount = totalPrice.multiply(recommenVip).divide(new BigDecimal(100)).intValue();
            Integer goldCoin =  wxUser.getGoldCoin();
            if (amount > 0) {
                Integer goldCoin1 = amount + goldCoin;
                wxUser.setGoldCoin(goldCoin1);
                wxUserService.updateWxUser(wxUser);

                //金币日志
                UserGoldLog userGoldLog = new UserGoldLog();
                userGoldLog.setOldBalance(new BigDecimal(goldCoin));
                userGoldLog.setChangeBalance(new BigDecimal(amount));
                userGoldLog.setNewBalance(new BigDecimal(goldCoin1));
                userGoldLog.setType(typeMoney);//购买会员
                userGoldLog.setCreated(new Date());
                userGoldLog.setUserId(wxUser.getMid());
                String s2 = s1 +"id:" + wxOrder.getUserId();
                userGoldLog.setRemark(s2);
                userGoldLog.setFromSourceId(wxOrder.getUserId() + "");//购买人
                userGoldLogService.insertUserGoldLog(userGoldLog);

                if (System.getProperty("os.name")!= null && !System.getProperty("os.name").toLowerCase().startsWith("windows")){
                    // 金币到账提醒
                    if (StringUtils.isNotEmpty(wxUser.getTsOpenid()) && wxUser.getStatus() == 1) {
                        ReceiveOrderVo1 receiveOrderVo1 = new ReceiveOrderVo1();
                        receiveOrderVo1.setAmount1(amount.toString());
                        receiveOrderVo1.setThing11(s1);
                        Date date1 = new Date();
                        String s = DateUtils.parseDateToStr(DateUtils.YYYY_MM_DD_HH_MM_SS3, date1);
                        receiveOrderVo1.setTime3(s);
                        String openid = wxUser.getTsOpenid();
                        //gzhPushMessageService.SendWxMsg1(openid, receiveOrderVo1);
                    }
                }
            }
        }

    }

    /**
     *  //合伙人奖励
     * @param wxUser
     * @param totalPrice
     * @param wxOrder
     *  type  1 团队奖励   2.合伙人直推合伙人
     */
    public void hehuorenjiangli(WxUser wxUser,BigDecimal totalPrice,WxOrder wxOrder,Integer type){

        MyCyhPartner myCyhPartner = myCyhPartnerService.selectMyCyhPartnerById(wxUser.getPartnerVip());
        BigDecimal teamRewards = null;
        Integer typeMoney = null;
        //11推荐官,12购买合伙人,13推荐官团队奖励,14合伙人团队奖励,15股东团队奖励
        String s1 ="";

        if (type.equals(1)){
            teamRewards = myCyhPartner.getTeamRewards();//1团队奖励
            s1= "成员购买会员,合伙人获得团队奖励";
            typeMoney = 14;
        }else if (type.equals(2)){
            teamRewards = myCyhPartner.getOnePartner();//2合伙人直推合伙人
            s1= "分享购买合伙人,合伙人获得奖励";
            typeMoney = 12;
        }else if (type.equals(5)){
            //分享购买商家会员,合伙人获得团队奖励
            teamRewards = myCyhPartner.getTeamRewards();//
            s1= "分享购买商家会员,合伙人获得团队奖励";
            typeMoney = 14;
        }else if (type.equals(6)){
            teamRewards = myCyhPartner.getMerchant();//
            s1= "分享购买商家会员,合伙人获得奖励";
            typeMoney = 5;
        }

        else {
            teamRewards = new BigDecimal(0);
        }

        //合伙人的团队奖励
        Integer amount = totalPrice.multiply(teamRewards).divide(new BigDecimal(100)).intValue();
        Integer goldCoin =  wxUser.getGoldCoin();
        if (amount > 0) {

            Integer goldCoin4 = amount + goldCoin;
            wxUser.setGoldCoin(goldCoin4);
            wxUserService.updateWxUser(wxUser);


            //金币日志
            UserGoldLog userGoldLog1 = new UserGoldLog();
            userGoldLog1.setOldBalance(new BigDecimal(goldCoin));
            userGoldLog1.setChangeBalance(new BigDecimal(amount));
            userGoldLog1.setNewBalance(new BigDecimal(goldCoin4));
            userGoldLog1.setType(typeMoney);////购买会员
            userGoldLog1.setCreated(new Date());
            userGoldLog1.setUserId(wxUser.getMid());
            String s2 = s1 +"id:" + wxOrder.getUserId();
            userGoldLog1.setRemark(s2);
            userGoldLog1.setFromSourceId(wxOrder.getUserId() + "");//购买人
            userGoldLogService.insertUserGoldLog(userGoldLog1);

            if (System.getProperty("os.name")!= null && !System.getProperty("os.name").toLowerCase().startsWith("windows")){
                // 金币到账提醒
                if (StringUtils.isNotEmpty(wxUser.getTsOpenid()) && wxUser.getStatus() == 1) {
                    ReceiveOrderVo1 receiveOrderVo1 = new ReceiveOrderVo1();
                    receiveOrderVo1.setAmount1(amount.toString());
                    receiveOrderVo1.setThing11(s1);
                    Date date1 = new Date();
                    String s = DateUtils.parseDateToStr(DateUtils.YYYY_MM_DD_HH_MM_SS3, date1);
                    receiveOrderVo1.setTime3(s);
                    String openid = wxUser.getTsOpenid();
                    //gzhPushMessageService.SendWxMsg1(openid, receiveOrderVo1);
                }
            }


        }
    }

    /**
     *  推荐官奖励
     * @param wxUser
     * @param totalPrice
     * @param wxOrder
     */
    public void tuijianguanjiangli(WxUser wxUser,BigDecimal totalPrice,WxOrder wxOrder,Integer type){
        MyCyhPromotionDor myCyhPromotionDor = myCyhPromotionDorService.selectMyCyhPromotionDorById(wxUser.getPromoLevel());
        if (myCyhPromotionDor !=null && myCyhPromotionDor.getIsEnable().equals(1)){
            BigDecimal teamRewards = null;
            ////11推荐官,12购买合伙人,13推荐官团队奖励,14合伙人团队奖励,15股东团队奖励
            Integer typeMoney = null;
            //合伙人的团队奖励
            //
            Integer goldCoin =  wxUser.getGoldCoin();

            String s1 = "";

            if (type.equals(1)){
                teamRewards = myCyhPromotionDor.getTeamRewards();
                s1= "分享购买会员,推荐官获得团队奖励";
                typeMoney = 13;
            }else if (type.equals(2)){
                teamRewards = myCyhPromotionDor.getTeamRewards();
                s1= "分享购买商家会员,推荐官获得团队奖励";
                typeMoney = 13;
            }else if (type.equals(3)){
                teamRewards = myCyhPromotionDor.getMerchant();
                s1= "分享购买商家会员,推荐官获得奖励";
                typeMoney = 5;
            }
            else {
                teamRewards = new BigDecimal(0);
            }

            Integer amount = totalPrice.multiply(teamRewards).divide(new BigDecimal(100)).intValue();
            if (amount >0){
                Integer goldCoin4 = amount + goldCoin;
                wxUser.setGoldCoin(goldCoin4);
                wxUserService.updateWxUser(wxUser);


                //金币日志
                UserGoldLog userGoldLog1 = new UserGoldLog();
                userGoldLog1.setOldBalance(new BigDecimal(goldCoin));
                userGoldLog1.setChangeBalance(new BigDecimal(amount));
                userGoldLog1.setNewBalance(new BigDecimal(goldCoin4));
                userGoldLog1.setType(typeMoney);//
                userGoldLog1.setCreated(new Date());
                userGoldLog1.setUserId(wxUser.getMid());
                String s2 = s1 +"id:" + wxOrder.getUserId();
                userGoldLog1.setRemark(s2);
                userGoldLog1.setFromSourceId(wxOrder.getUserId() + "");//购买人
                userGoldLogService.insertUserGoldLog(userGoldLog1);

                if (System.getProperty("os.name")!= null && !System.getProperty("os.name").toLowerCase().startsWith("windows")){
                    // 金币到账提醒
                    if (StringUtils.isNotEmpty(wxUser.getTsOpenid()) && wxUser.getStatus() == 1) {
                        ReceiveOrderVo1 receiveOrderVo1 = new ReceiveOrderVo1();
                        receiveOrderVo1.setAmount1(amount.toString());
                        receiveOrderVo1.setThing11(s1);
                        Date date1 = new Date();
                        String s = DateUtils.parseDateToStr(DateUtils.YYYY_MM_DD_HH_MM_SS3, date1);
                        receiveOrderVo1.setTime3(s);
                        String openid = wxUser.getTsOpenid();
                        //gzhPushMessageService.SendWxMsg1(openid, receiveOrderVo1);
                    }
                }
            }


        }
    }

    /**
     *
     * @param wxUser 的钱用户
     * @param totalPrice
     * @param wxOrder
     */
    public void huiyuanjiangli(WxUser wxUser,BigDecimal totalPrice,WxOrder wxOrder,Integer type){
        MyCyhVip myCyhVip1 = myCyhVipService.selectMyCyhVipByLevel(wxUser.getVipLevel());
        if (myCyhVip1 !=null){
            Integer typeMoney = null;
            BigDecimal teamRewards = null;
            String s1 = "";

            if (type.equals(1)){
                teamRewards = myCyhVip1.getCommission();
                s1= "分享购买会员,会员获得奖励";
                typeMoney = 4;
            }else if (type.equals(2)){
                teamRewards = myCyhVip1.getCommission();
                s1= "分享购买商家会员,会员获得奖励";
                typeMoney = 5;
            }else {
                teamRewards =new BigDecimal(0);
            }

            Integer change = totalPrice.multiply(teamRewards).divide(new BigDecimal(100)).intValue();
            if (change>0){
                Integer goldCoin = wxUser.getGoldCoin();
                Integer total = goldCoin + change;
                wxUser.setGoldCoin(total);
                wxUserService.updateWxUser(wxUser);

                //金币日志
                UserGoldLog userGoldLog = new UserGoldLog();
                userGoldLog.setOldBalance(new BigDecimal(goldCoin));
                userGoldLog.setChangeBalance(new BigDecimal(change));
                userGoldLog.setNewBalance(new BigDecimal(total));
                userGoldLog.setType(typeMoney);//4购买会员佣金
                userGoldLog.setCreated(new Date());
                userGoldLog.setUserId(wxUser.getMid());
                String s2 = s1 +"id:" + wxOrder.getUserId();
                userGoldLog.setRemark(s2);//活动id
                userGoldLog.setFromSourceId(wxOrder.getUserId() + "");//购买人
                userGoldLogService.insertUserGoldLog(userGoldLog);

                if (System.getProperty("os.name")!= null && !System.getProperty("os.name").toLowerCase().startsWith("windows")){
                    // 金币到账提醒
                    if (StringUtils.isNotEmpty(wxUser.getTsOpenid()) && wxUser.getStatus() == 1) {
                        ReceiveOrderVo1 receiveOrderVo1 = new ReceiveOrderVo1();
                        receiveOrderVo1.setAmount1(change.toString());
                        receiveOrderVo1.setThing11(s1);
                        Date date1 = new Date();
                        String s = DateUtils.parseDateToStr(DateUtils.YYYY_MM_DD_HH_MM_SS3, date1);
                        receiveOrderVo1.setTime3(s);
                        String openid = wxUser.getTsOpenid();
                        //gzhPushMessageService.SendWxMsg1(openid, receiveOrderVo1);
                    }
                }

            }


        }

    }

    @Transactional
    @Override
    public Map<String, Object> payOrder(WxOrder wxOrder, HttpServletRequest request) {

        WxUser wxUser = SecurityUtils.getLoginUser().getWxUser();
        //分
        BigDecimal totalPrice = wxOrder.getTotalPrice();

        if (Objects.isNull(totalPrice)) {
            throw new CustomException("总价不能为空", 400);
        }

        /*if (totalPrice.compareTo(new BigDecimal(1)) < 0){
            throw new CustomException("充值金额不能小于1元", 400);
        }*/
        PayObject payObject = wxOrder.getPayObject();
        WxOrder wxOrder1 = new WxOrder();
        System.out.println(payObject);//PayObject(manPrice=299, manNum=2, womanPrice=1, womanNum=2, underagePrice=0, underageNum=2)
        if (!Objects.isNull(payObject)) {
            BigDecimal total = new BigDecimal("0");
            if (payObject.getManPrice() != null && payObject.getManNum() != null) {
                total = total.add(payObject.getManPrice().multiply(new BigDecimal(payObject.getManNum())));

            }
            if (payObject.getWomanPrice() != null && payObject.getWomanNum() != null) {
                total = total.add(payObject.getWomanPrice().multiply(new BigDecimal(payObject.getWomanNum())));
            }
            if (payObject.getUnderagePrice() != null && payObject.getUnderageNum() != null) {
                total = total.add(payObject.getUnderagePrice().multiply(new BigDecimal(payObject.getUnderageNum())));
            }

            if (total.compareTo(totalPrice) != 0) {
                throw new CustomException("计算价格有误", 400);
            }
            wxOrder1.setActObj(JSONObject.toJSONString(payObject));
        }

        // 参加活动
        if (wxOrder.getType().equals(3)) {
            MyCyhActivity myCyhActivity = myCyhActivityService.selectMyCyhActivityById(Integer.valueOf(wxOrder.getRemark()));

            MyCyhActivitySign myCyhActivitySign = myCyhActivitySignService.selectMyCyhActivitySignById(Integer.valueOf(wxOrder.getTransactionId()));
            if (myCyhActivitySign != null && !myCyhActivity.getCate().equals("3")) {
                //Date ctime = myCyhActivitySign.getCtime();
                //Date date = DateUtils.addDays(ctime, 1);
                Integer ticketId = myCyhActivitySign.getTicketId();
                if (!Objects.isNull(ticketId)) {
                    synchronized (this) {
                        MyCyhTicket myCyhTicket = myCyhTicketService.selectMyCyhTicketById(ticketId);
                        if (myCyhTicket != null) {
                            Integer numbers = myCyhTicket.getNumbers();//已报名人数
                            Integer totalNum = myCyhTicket.getTotalNum();
                            if (totalNum - numbers <= 0) {
                                throw new CustomException("票种人数已满", 400);
                            }
                            if (myCyhActivitySign.getNums() > (totalNum - numbers)) {
                                throw new CustomException("票种人数超额", 400);
                            }
                        }
                    }

                } else {

                    Integer nums = myCyhActivity.getNums(); //可报名总人数',
                    Integer leave = myCyhActivity.getLeave();//'已报名人数',
                    if (leave >= nums) {
                        throw new CustomException("活动人数已满", 400);
                    }

                    if (myCyhActivitySign.getNums() > (nums - leave)) {
                        throw new CustomException("报名活动人数已满", 400);
                    }
                }
            }
        }

        String ipAddr = IpUtils.getIpAddr(request);
        MyWxPayConfigUtil2 myWxPayConfigUtil = new MyWxPayConfigUtil2();
        //myWxPayConfigUtil.setAppId(WxConfig.APP_ID);
        myWxPayConfigUtil.setTxamt(String.valueOf(totalPrice.multiply(new BigDecimal(100)).intValue()));
        String orderId = String.valueOf(idWorker.nextId());
        Date date = new Date();
        myWxPayConfigUtil.setOrderNo(orderId);
        myWxPayConfigUtil.setOpenid(wxUser.getOpenid());
        myWxPayConfigUtil.setDate(date);
        myWxPayConfigUtil.setIp(ipAddr);
        try {

            wxOrder1.setTotalPrice(totalPrice);
            wxOrder1.setCreateTime(date);
            wxOrder1.setUserId(wxUser.getMid());
            wxOrder1.setTotalPrice(totalPrice);
            //0待支付,1已支付,2已退款,3关闭支付,4已删除"
            wxOrder1.setStatus(0);
            wxOrder1.setCreateTime(date);
            wxOrder1.setId(orderId);
            wxOrder1.setExpireTime(DateUtil.adjustDateByHour(date, 24, 1));
            wxOrder1.setType(wxOrder.getType());
            wxOrder1.setRemark(wxOrder.getRemark());
            //wxOrderMapper.insertWxOrder(wxOrder1);
            wxOrder1.setCarId(wxOrder.getCarId());
            wxOrder1.setTransactionId(wxOrder.getTransactionId());
            wxOrder1.setMerchantId(wxOrder.getMerchantId());

            Map<String, Object> map = PayUtil2.test5(myWxPayConfigUtil);
            if (map.get("code").equals("000000")) {
                String s = JSONObject.toJSONString(map.get("data"));

                Map<String,String> map1= JSONObject.parseObject(s,Map.class);
                System.out.println("map1:"+map1);
                //map1:{agetId=6100518974, getPrepayId=1, jsapiAppid=wxc53e21e72bf9cba9,
                // orderNo=20241101TTT8mesa, orderTime=20241101112543, threeOrderNo=1852190256204349440,
                // jsapiPaySign=C5577/Fmtn9Lwk/sOAVzwLv/a6NQAs9DmO6AtoskK0Nv98RS4eKneCJMg6egoyGAvygrWlWrXsN+MRXkneI6Xb2mGvr2hn4qs9g2Aox+oL7ZjrFLj8mVGGGXDZ2mcUgzMIFfcXa1QwLGD47rWZ/c8rJT2LIFbe7RAykMnX77MnZXQih1eBFI7aaofPB1LMK7+IqjBeyU7VqrBf0Pv7SJnnX9MEPQw5s+GwlgvA/DOFz/Qqw0q2b1UZMEIfcHbpMENLbAuzUTP4xwLcinTBUFRJD03L+w+ghklevlGtPu3QA4tOPlGM6GLp7MNUTTK7h9QzEauCQ2XHjypUBleer3kg==,
                // prePayId=wx01112543528106078f6b6be55a1df70000,
                // jsapiSignType=RSA, jsapiNoncestr=204ccccb3bab47d38cb22c4c8d27463c, jsapiTimestamp=1730431543,
                // jsapiPackage=prepay_id=wx01112543528106078f6b6be55a1df70000}

                wxOrder1.setPrepayId(map1.get("prePayId"));// 预支付id
                wxOrder1.setOrderNo(map1.get("orderNo"));// 国通交易订单号

                //wxOrder.setPayStr(s);
                wxOrderMapper.insertWxOrder(wxOrder1);
                // 监听订单过期 修改订单状态
                redisCache.setCacheObject("orderId:" + wxOrder1.getId(), "abc", 30, TimeUnit.MINUTES);
            } else {
                throw new CustomException((String) map.get("msg"), 400);
            }
            map.put("orderId", wxOrder.getId());

            return map;
        } catch (Exception e) {
            e.printStackTrace();
        }

        throw new CustomException("支付异常", 400);
    }

    @Override
    public List<WxOrder> myOrder(Integer mid) {
        WxOrder wxOrder = new WxOrder();
        wxOrder.setUserId(mid);
        List<WxOrder> wxOrders = selectWxOrderList(wxOrder);

        return wxOrders;
    }



    @Transactional
    @Override
    public  void  refund(WxOrder wxOrder) {
        MyCyhActivity myCyhActivity = myCyhActivityService.selectMyCyhActivityById(Integer.valueOf(wxOrder.getRemark()));
        if (myCyhActivity !=null && !myCyhActivity.getCate().equals("3")){
            if (new Date().after(myCyhActivity.getAtimeStart())){

                throw new CustomException("活动已开始暂不退款");
            }else {

                MyWxPayConfigUtil2 myWxPayConfigUtil = new MyWxPayConfigUtil2();
                myWxPayConfigUtil.setDate(new Date());
                myWxPayConfigUtil.setOrderNo(wxOrder.getOrderNo());
                myWxPayConfigUtil.setOrderId(wxOrder.getId());
                myWxPayConfigUtil.setTxamt(wxOrder.getTotalPrice().multiply(new BigDecimal(100)).toString());
                Map<String, String> map = PayUtil2.refound(myWxPayConfigUtil);
                //  退款map:{logNo=202404104236647013, mercId=800551000056528, amount=1, tradeNo=1777994133571371008, subject=, goodsTag=, message=交易退款成功, signValue=fb4d0994e271a7c418ccf58f438c6304, result=S, returnCode=000000, total_amount=1, selOrderNo=, sysTime=20240410173848, attach=, txnAmt=1}
                String returnCode = map.get("returnCode");
                String result = map.get("result");
                if (!returnCode.equals("000000") ||  !result.equals("S")){
                    throw new CustomException(map.get("message"));
                }

                /*try {
                    Thread.sleep(100L);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }*/

                //关联到活动保名的id
                String transactionId = wxOrder.getTransactionId();
                if (StringUtils.isNotEmpty(transactionId)){
                    MyCyhActivitySign myCyhActivitySign = myCyhActivitySignService.selectMyCyhActivitySignById(Integer.valueOf(transactionId));
                    if (myCyhActivitySign !=null){
                        if (myCyhActivitySign.getIsPay().equals(1)){

                            //更新报名的人
                            Integer leave = myCyhActivity.getLeave();
                            Integer nums = myCyhActivitySign.getNums();
                            leave -= nums;
                            myCyhActivity.setLeave(leave);
                            myCyhActivityService.updateMyCyhActivity(myCyhActivity);

                            myCyhActivitySign.setIsPay(2);//已退款
                            int i = myCyhActivitySignService.updateMyCyhActivitySign(myCyhActivitySign);
                            //System.out.println("报名标记:"+i);

                            wxOrder.setStatus(2);
                            wxOrderMapper.updateWxOrder(wxOrder);
                            //System.out.println("订单标记:"+i);


                            Integer ticketId = myCyhActivitySign.getTicketId();
                            if (!Objects.isNull(ticketId)){
                                MyCyhTicket myCyhTicket = myCyhTicketService.selectMyCyhTicketById(ticketId);
                                if (  myCyhTicket != null){

                                    Integer numbers = myCyhTicket.getNumbers();
                                    Integer nums1 = myCyhActivitySign.getNums();
                                    numbers -=nums1;
                                    myCyhTicket.setNumbers(numbers);
                                    myCyhTicketService.updateMyCyhTicket(myCyhTicket);
                                }


                            }

                            UserGoldLog userGoldLog =new UserGoldLog();
                            userGoldLog.setSignId(myCyhActivitySign.getId());
                            UserGoldLog goldLog = userGoldLogService.selectUserGoldLogBySign(myCyhActivitySign.getId());
                            if (goldLog !=null){
                                goldLog.setStatus(3);//返回到系统
                                userGoldLogService.updateUserGoldLog(goldLog);
                            }

                        }
                    }
                }


            }


        }

    }



    @Override
    public List<WxOrder> selectWxOrderListWeb(WxOrder wxOrder) {
        return wxOrderMapper.selectWxOrderListWeb(wxOrder);
    }

    @Transactional
    @Override
    public void updateNotify(WxOrder wxOrder) {
        wxOrderMapper.updateWxOrder(wxOrder);
        if (wxOrder.getType().equals(1)) {
            //商家入驻
            MyCyhShop myCyhShop = myCyhShopService.selectMyCyhShopById(Integer.valueOf(wxOrder.getRemark()));
            myCyhShop.setAuditStatus("1");
            //myCyhShop.setPlanId(Integer.valueOf(wxOrder.getRemark()));
            Date expireTime = myCyhShop.getExpireTime();
            Date date = null;
            if (Objects.isNull(expireTime)) {
                date = DateUtils.addYears(new Date(), 1);

            } else {
                if (expireTime.before(new Date())) {
                    //过期
                    date = DateUtils.addYears(new Date(), 1);
                } else {
                    //没过期
                    date = DateUtils.addYears(expireTime, 1);
                }
            }
            //入驻的时候商家编号
            String code = "";
            Integer planId = myCyhShop.getPlanId();
            if (planId != null) {
                if (planId.equals(1)) {
                    MyCyhSerialNumber myCyhSerialNumber = myCyhSerialNumberService.selectMyCyhSerialNumberById(1);
                    Integer vlaue = myCyhSerialNumber.getVlaue();
                    vlaue++;
                    myCyhSerialNumber.setVlaue(vlaue);
                    code = myCyhSerialNumber.getName() + vlaue;
                    myCyhSerialNumberService.updateMyCyhSerialNumber(myCyhSerialNumber);

                } else if (planId.equals(2)) {
                    MyCyhSerialNumber myCyhSerialNumber = myCyhSerialNumberService.selectMyCyhSerialNumberById(2);
                    Integer vlaue = myCyhSerialNumber.getVlaue();
                    vlaue++;
                    myCyhSerialNumber.setVlaue(vlaue);
                    code = myCyhSerialNumber.getName() + vlaue;
                    myCyhSerialNumberService.updateMyCyhSerialNumber(myCyhSerialNumber);

                } else if (planId.equals(3)) {
                    MyCyhSerialNumber myCyhSerialNumber = myCyhSerialNumberService.selectMyCyhSerialNumberById(3);
                    Integer vlaue = myCyhSerialNumber.getVlaue();
                    vlaue++;
                    myCyhSerialNumber.setVlaue(vlaue);
                    code = myCyhSerialNumber.getName() + vlaue;
                    myCyhSerialNumberService.updateMyCyhSerialNumber(myCyhSerialNumber);
                }
            }

            myCyhShop.setExpireTime(date);
            myCyhShop.setCode(code);
            myCyhShop.setUserId(wxOrder.getUserId());//商家用户
            myCyhShopService.updateMyCyhShop(myCyhShop);


            //上级的佣金
            synchronized (this) {
                Integer userId = wxOrder.getUserId();
                WxUser wxUser = wxUserService.selectWxUserById(userId);
                wxUser.setIsMerchant(1);
                wxUserService.updateWxUser(wxUser);
                if (System.getProperty("os.name")!= null && !System.getProperty("os.name").toLowerCase().startsWith("windows")){
                    //发给管理员
                    ReceiveOrderVo receiveOrderVo = new ReceiveOrderVo();
                    receiveOrderVo.setAmount5(wxOrder.getTotalPrice().toString());
                    receiveOrderVo.setNumber9(wxUser.getPhone());
                    receiveOrderVo.setThing3("商家入驻");
                    String s11 = DateUtils.parseDateToStr(DateUtils.YYYY_MM_DD_HH_MM_SS3, new Date());
                    receiveOrderVo.setTime4(s11);
                    String openid11 = "oHnzZ6HemJ3VIiEC4bj8FOj85-kM";//廖春香
                    //gzhPushMessageService.SendWxMsg(openid11, receiveOrderVo);
                }


                Integer introMid = wxUser.getIntroMid();
                if (introMid !=null && introMid >0){
                    WxUser wxUser1 = wxUserService.selectWxUserById(introMid);
                    if (wxUser1 !=null){
                        Integer goldCoin = wxUser1.getGoldCoin();
                        BigDecimal totalPrice = wxOrder.getTotalPrice();
                        Integer total = 0;
                        Integer change = 0;
                        //是股东
                        if (wxUser1.getStockHolder() != null && wxUser1.getStockHolder().equals(1)) {

                            MyCyhHolder myCyhHolder = myCyhHolderService.selectMyCyhHolderById(1);
                            if (myCyhHolder != null) {
                                //股东直推商家
                                gudongjiangli(wxUser1,totalPrice,wxOrder,6);//分享购买商家会员,股东获得奖励
                            }

                        } else  if (wxUser1.getIsPartner() !=null && wxUser1.getPartnerVip()!=null &&
                            wxUser1.getIsPartner().equals(1) && wxUser1.getExpireTime2() !=null  &&
                            wxUser1.getExpireTime2().after(new Date())) {
                            //合伙人直推商家会员
                            hehuorenjiangli(wxUser1,totalPrice,wxOrder,6);//分享购买商家会员,合伙人获得奖励

                            //找合伙人的上级股东分团队奖励
                            if (wxUser1.getLine() !=null && wxUser1.getLine() >0){
                                WxUser wxUser2 = wxUserService.selectWxUserById(wxUser1.getLine());
                                if (wxUser2 !=null && wxUser2.getStockHolder() !=null && wxUser2.getStockHolder().equals(1)){
                                    gudongjiangli(wxUser2,totalPrice,wxOrder,5);//分享购买商家会员,股东获得团队奖励
                                }
                            }



                        }else if (wxUser1.getPromoDor() !=null && wxUser1.getPromoDor().equals(1) &&
                            wxUser1.getPromoLevel()!=null && wxUser1.getExpireTime1()!=null && wxUser1.getExpireTime1().after(new Date())){
                            //推荐官直推商家会员
                            tuijianguanjiangli(wxUser1,totalPrice,wxOrder,3);//分享购买商家会员,推荐官获得奖励


                            if (wxUser1.getLineTwo() !=null && wxUser1.getLineTwo() >0){
                                WxUser wxUser2 = wxUserService.selectWxUserById(wxUser1.getLineTwo());
                                if (wxUser2 !=null && wxUser2.getIsPartner() !=null && wxUser2.getIsPartner().equals(1)
                                    && wxUser2.getExpireTime2() !=null && wxUser2.getExpireTime2().after(new Date()) ){
                                    //合伙人获得团队奖励
                                    hehuorenjiangli(wxUser2,totalPrice,wxOrder,5);//分享购买商家会员,合伙人获得团队奖励
                                }
                            }
                            if (wxUser1.getLine() !=null && wxUser1.getLine() >0){
                                WxUser wxUser2 = wxUserService.selectWxUserById(wxUser1.getLine());
                                if (wxUser2 !=null && wxUser2.getStockHolder() !=null && wxUser2.getStockHolder().equals(1) ){
                                    //股东获得团队奖励
                                    gudongjiangli(wxUser2,totalPrice,wxOrder,5);//分享购买商家会员,股东获得团队奖励
                                }
                            }



                        }else if (!Objects.isNull(wxUser1.getVipLevel()) && wxUser1.getExpireTime() !=null &&
                            wxUser1.getExpireTime().after(new Date())) {
                            huiyuanjiangli(wxUser1,totalPrice,wxOrder,2);//分享购买商家会员,会员获得奖励



                            //推荐官分团队奖励
                            if (wxUser1.getLineThree() !=null && wxUser1.getLineThree()>0){
                                WxUser wxUser2 = wxUserService.selectWxUserById(wxUser1.getLineThree());
                                if  (wxUser2 !=null && wxUser2.getPromoDor() !=null && wxUser2.getPromoDor().equals(1)
                                    && wxUser2.getExpireTime1() !=null && wxUser2.getExpireTime1().after(new Date()) ){
                                    tuijianguanjiangli(wxUser,totalPrice,wxOrder,2);//分享购买商家会员,推荐官获得团队奖励
                                }

                            }

                            //合伙人获得团队奖励
                            if (wxUser1.getLineTwo() !=null && wxUser1.getLineTwo() >0){
                                WxUser wxUser2 = wxUserService.selectWxUserById(wxUser1.getLineTwo());
                                if (wxUser2 !=null && wxUser2.getIsPartner() !=null && wxUser2.getIsPartner().equals(1)
                                    && wxUser2.getExpireTime2() !=null && wxUser2.getExpireTime2().after(new Date()) ){
                                    hehuorenjiangli(wxUser2,totalPrice,wxOrder,5);//分享购买商家会员,合伙人获得团队奖励
                                }
                            }

                            //股东获得团队奖励
                            if (wxUser1.getLine() !=null && wxUser1.getLine() >0){
                                WxUser wxUser2 = wxUserService.selectWxUserById(wxUser1.getLine());
                                if (wxUser2 !=null && wxUser2.getStockHolder() !=null && wxUser2.getStockHolder().equals(1) ){

                                    gudongjiangli(wxUser2,totalPrice,wxOrder,5);//分享购买商家会员,股东获得团队奖励
                                }
                            }



                        }

                    }
                }

                /*MyCyhMerchantShare myCyhMerchantShare = myCyhMerchantShareService.selectOneLastByUserId(wxOrder.getUserId());
                if (myCyhMerchantShare != null) {
                    //WxUser wxUser1 = wxUserService.selectWxUserById(introMid);
                    WxUser wxUser1 = wxUserService.selectWxUserById(myCyhMerchantShare.getShareId());

                    //一天以后的时间
                    Date endTime = DateUtil.adjustDateByHour(myCyhMerchantShare.getCreated(), 24, 1);
                    if ( new Date().before(endTime)) {

                    }

                }*/
            }


        } else if (wxOrder.getType().equals(2)) {
            //副牌 (不)送会员
            MyCyhMark myCyhMark = new MyCyhMark();
            myCyhMark.setCarId(wxOrder.getCarId());
            myCyhMark.setNumber(wxOrder.getRemark());

            //OrderObject orderObject = wxOrder.getOrderObject();

            synchronized (this) {
                List<MyCyhMark> myCyhMarks = myCyhMarkService.selectMyCyhMarkList(myCyhMark);
                if (myCyhMarks.size() > 0) {
                    // 被买了 退款

                } else {
                    myCyhMark.setUserId(wxOrder.getUserId());
                    if (StringUtils.isNotEmpty(wxOrder.getCarId())) {
                        myCyhMark.setCarId(wxOrder.getCarId());
                    }
                    myCyhMarkService.insertMyCyhMark(myCyhMark);

                    /*MyCarBook myCarBook = myCarBookService.selectMyCarBookByUserId(wxOrder.getUserId());

                    if (myCarBook !=null){
                        myCarBook.setSubCard(wxOrder.getRemark());
                        myCarBookService.updateMyCarBook(myCarBook);
                    }*/

                    /*WxUser wxUser = wxUserService.selectWxUserById(wxOrder.getUserId());
                    wxUser.setFupai(wxOrder.getRemark());
                    //不送会员
                    wxUser.setVipLevel(1);
                    wxUser.setExpireTime(DateUtils.addYears(new Date(), 1));
                    wxUserService.updateWxUser(wxUser);*/

                }
            }

            //上级的佣金
            synchronized (this) {
                Integer userId = wxOrder.getUserId();
                WxUser wxUser = wxUserService.selectWxUserById(userId);

                //发给管理员
                ReceiveOrderVo receiveOrderVo = new ReceiveOrderVo();
                receiveOrderVo.setAmount5(wxOrder.getTotalPrice().toString());
                receiveOrderVo.setNumber9(wxUser.getPhone());
                receiveOrderVo.setThing3("购买副牌");
                String s11 = DateUtils.parseDateToStr(DateUtils.YYYY_MM_DD_HH_MM_SS3, new Date());
                receiveOrderVo.setTime4(s11);
                String openid11 = "oHnzZ6HemJ3VIiEC4bj8FOj85-kM";//廖春香
                //gzhPushMessageService.SendWxMsg(openid11, receiveOrderVo);

                Integer introMid = wxUser.getIntroMid();
                if (introMid != null && introMid > 0) {
                    WxUser wxUser1 = wxUserService.selectWxUserById(introMid);
                    // 有会员登记才能得佣金
                    if (wxUser1 != null && !Objects.isNull(wxUser1.getVipLevel()) && wxUser1.getExpireTime().after(new Date())) {
                        Integer goldCoin = wxUser1.getGoldCoin();
                        BigDecimal totalPrice = wxOrder.getTotalPrice();
                        MyCyhVip myCyhVip = myCyhVipService.selectMyCyhVipByLevel(wxUser1.getVipLevel());
                        if (myCyhVip != null) {
                            BigDecimal change = totalPrice.multiply(myCyhVip.getCommission()).divide(new BigDecimal(100));
                            Integer total = goldCoin + change.intValue();
                            wxUser1.setGoldCoin(total);
                            wxUserService.updateWxUser(wxUser1);

                            //金币日志
                            UserGoldLog userGoldLog = new UserGoldLog();
                            userGoldLog.setOldBalance(new BigDecimal(goldCoin));
                            userGoldLog.setChangeBalance(new BigDecimal(change.intValue()));
                            userGoldLog.setNewBalance(new BigDecimal(total));
                            userGoldLog.setType(6);//变动类型，1提现，2活动佣金,3充值，4购买会员佣金,5商家入驻佣金,6购买副牌佣金等,
                            userGoldLog.setCreated(new Date());
                            userGoldLog.setUserId(introMid);
                            userGoldLog.setRemark("分享购买副牌佣金");//
                            userGoldLog.setFromSourceId(userId + "");//购买人
                            userGoldLogService.insertUserGoldLog(userGoldLog);

                            // 金币到账提醒
                            if (StringUtils.isNotEmpty(wxUser1.getTsOpenid()) && wxUser1.getStatus() == 1) {
                                ReceiveOrderVo1 receiveOrderVo1 = new ReceiveOrderVo1();
                                receiveOrderVo1.setAmount1(change.toString());
                                receiveOrderVo1.setThing11("分享购买副牌佣金");
                                Date date1 = new Date();
                                String s = DateUtils.parseDateToStr(DateUtils.YYYY_MM_DD_HH_MM_SS3, date1);
                                receiveOrderVo1.setTime3(s);
                                String openid = wxUser1.getTsOpenid();
                                //gzhPushMessageService.SendWxMsg1(openid, receiveOrderVo1);
                            }
                        }
                    }
                }
            }

        } else if (wxOrder.getType().equals(3)) {
            //参加活动
            String remark = wxOrder.getRemark(); //活动id
            WxUser wxUser = wxUserService.selectWxUserById(wxOrder.getUserId());

            //发给管理员
            ReceiveOrderVo receiveOrderVo = new ReceiveOrderVo();
            receiveOrderVo.setAmount5(wxOrder.getTotalPrice().toString());
            receiveOrderVo.setNumber9(wxUser.getPhone());
            receiveOrderVo.setThing3("参加活动");
            String s11 = DateUtils.parseDateToStr(DateUtils.YYYY_MM_DD_HH_MM_SS3, new Date());
            receiveOrderVo.setTime4(s11);
            String openid11 = "oHnzZ6HemJ3VIiEC4bj8FOj85-kM";//廖春香
            //gzhPushMessageService.SendWxMsg(openid11, receiveOrderVo);
            /*PayObject payObject = wxOrder.getPayObject();
            Integer ticketId =null;*/
            MyCyhActivity myCyhActivity = null;
            // 最后一个
            //MyCyhActivitySign myCyhActivitySign = myCyhActivitySignService.selectByIdAndUserId(Integer.valueOf(remark), wxOrder.getUserId());
            MyCyhActivitySign myCyhActivitySign = myCyhActivitySignService.selectMyCyhActivitySignById(Integer.valueOf(wxOrder.getTransactionId()));
            synchronized (this) {
                //如果是公益活动分享人没有收益,购买者也不加积分
                myCyhActivity = myCyhActivityService.selectMyCyhActivityById(Integer.valueOf(remark));

                //MyCyhActivity myCyhActivity = myCyhActivityService.selectMyCyhActivityById(Integer.valueOf(remark));
                Integer leave = myCyhActivity.getLeave();
                if (myCyhActivitySign != null) {
                    Integer nums = myCyhActivitySign.getNums();
                    leave += nums;
                    //nums--;
                    myCyhActivity.setLeave(leave);
                    //myCyhActivity.setNums(nums);
                    myCyhActivityService.updateMyCyhActivity(myCyhActivity);

                    myCyhActivitySign.setIsPay(1);//0未支付,1已支付
                    myCyhActivitySignService.updateMyCyhActivitySign(myCyhActivitySign);

                }

            }
            Integer isUse = 0;
            //不是公益才走 且有折扣类型 1固定会员折扣,2会员等级折扣 3 无折扣 或者null
            if (myCyhActivitySign != null && !myCyhActivity.getCate().equals("3")) {
                Date ctime = myCyhActivitySign.getCtime();
                Date date = DateUtils.addDays(ctime, 1);
                Integer ticketId = myCyhActivitySign.getTicketId();
                if (!Objects.isNull(ticketId)) {
                    synchronized (this) {
                        MyCyhTicket myCyhTicket = myCyhTicketService.selectMyCyhTicketById(ticketId);
                        if (myCyhTicket != null) {
                            isUse = myCyhTicket.getIsUse();
                            Integer numbers = myCyhTicket.getNumbers();
                            Integer nums = myCyhActivitySign.getNums();
                            numbers = numbers + nums;
                            myCyhTicket.setNumbers(numbers);
                            myCyhTicketService.updateMyCyhTicket(myCyhTicket);
                        }
                    }

                }

                //上级的佣金
                synchronized (this) {
                    Integer shareId = myCyhActivitySign.getShareId();
                    if (!Objects.isNull(shareId)) {
                        WxUser wxUserShare = wxUserService.selectWxUserById(shareId);
                        if (wxUserShare != null) {
                            Integer amountType = myCyhActivity.getAmountType();
                            if (amountType !=null){
                                Integer goldCoin = wxUserShare.getGoldCoin();
                                BigDecimal change= new BigDecimal(0);
                                Integer total = 0;
                                if (amountType==1){
                                    //百分比
                                    BigDecimal commission = myCyhActivity.getCommission();
                                    if (commission != null && (commission.compareTo(new BigDecimal("0")) > 0) && !myCyhActivity.getCate().equals("3") && isUse == 0){
                                        if (myCyhActivitySign.getNums() >= 1) {
                                            //计算价格
                                            //change = change.multiply(new BigDecimal(myCyhActivitySign.getNums()));

                                            change = wxOrder.getTotalPrice().multiply(commission).divide(new BigDecimal(100)).multiply(new BigDecimal(myCyhActivitySign.getNums()));
                                        }

                                    }

                                }else if (amountType== 2){
                                    //固定活动佣金
                                    BigDecimal commission1 = myCyhActivity.getCommission1();
                                    if (commission1 != null && (commission1.compareTo(new BigDecimal("0")) > 0) && !myCyhActivity.getCate().equals("3") && isUse == 0){
                                        if (myCyhActivitySign.getNums() >= 1) {
                                            //计算价格
                                            change = commission1.multiply(new BigDecimal(myCyhActivitySign.getNums()));
                                        }

                                    }
                                }
                                if (change.intValue() >0){
                                    total = goldCoin + change.intValue();
                                    //wxUserShare.setGoldCoin(total);
                                    //wxUserService.updateWxUser(wxUserShare);//活动佣金冻结 后续释放

                                    //金币日志
                                    UserGoldLog userGoldLog = new UserGoldLog();
                                    userGoldLog.setOldBalance(new BigDecimal(goldCoin));
                                    userGoldLog.setChangeBalance(new BigDecimal(change.intValue()));
                                    userGoldLog.setNewBalance(new BigDecimal(total));
                                    userGoldLog.setType(2);//变动类型，1提现，2活动佣金,3充值，4购买会员佣金,5商家入驻佣金,6购买副牌佣金等,
                                    userGoldLog.setCreated(new Date());
                                    userGoldLog.setUserId(shareId);
                                    userGoldLog.setRemark("分享参加活动得佣金");//
                                    userGoldLog.setStatus(2);//活动冻结
                                    userGoldLog.setSignId(myCyhActivitySign.getId());//报名的id
                                    userGoldLog.setFromSourceId(remark);//活动id

                                    userGoldLogService.insertUserGoldLog(userGoldLog);

                                    // 金币到账提醒
                                    if (StringUtils.isNotEmpty(wxUserShare.getTsOpenid()) && wxUserShare.getStatus() == 1) {
                                        ReceiveOrderVo1 receiveOrderVo1 = new ReceiveOrderVo1();
                                        receiveOrderVo1.setAmount1(String.valueOf(change.intValue() ));
                                        receiveOrderVo1.setThing11("分享参加活动得佣金,活动结束后前往释放");
                                        Date date1 = new Date();
                                        String s = DateUtils.parseDateToStr(DateUtils.YYYY_MM_DD_HH_MM_SS3, date1);
                                        receiveOrderVo1.setTime3(s);
                                        String openid = wxUserShare.getTsOpenid();
                                        //gzhPushMessageService.SendWxMsg1(openid, receiveOrderVo1);
                                    }

                                }

                            }
                        }
                    }
                }
                // 活动有积分,不是公益活动, 不能用邀请码
                if (myCyhActivity.getScore() != null && myCyhActivity.getScore() > 0 && !myCyhActivity.getCate().equals("3") && isUse == 0) {
                    //加积分
                    Integer points = wxUser.getPoints();
                    //MyCyhSocre myCyhSocre = myCyhSocreService.selectMyCyhSocreByType(4);
                    //Integer changePoint = new BigDecimal(myCyhSocre.getScore()).multiply(wxOrder.getTotalPrice()).intValue()  ;
                    Integer changePoint = myCyhActivity.getScore();
                    Integer newPoint = points + changePoint;
                    wxUser.setPoints(newPoint);
                    wxUserService.updateWxUser(wxUser);
                    //积分日志
                    UserPointLog userPointLog = new UserPointLog();
                    userPointLog.setRemark("参加活动加积分");
                    userPointLog.setOldPoint(points);
                    userPointLog.setChangePoint(changePoint);
                    userPointLog.setNewPoint(newPoint);
                    userPointLog.setUserId(wxOrder.getUserId());
                    userPointLog.setType(4);
                    userPointLog.setCreated(new Date());
                    userPointLogService.insertUserPointLog(userPointLog);
                }

            }


        } else if (wxOrder.getType().equals(4)) {
            //购买会员
            String remark = wxOrder.getRemark(); //会员等级
            MyCyhVip myCyhVip = myCyhVipService.selectMyCyhVipByLevel(Integer.valueOf(remark));
            WxUser wxUser = wxUserService.selectWxUserById(wxOrder.getUserId());

            if (System.getProperty("os.name")!= null && !System.getProperty("os.name").toLowerCase().startsWith("windows")){
                //发给管理员
                ReceiveOrderVo receiveOrderVo = new ReceiveOrderVo();
                receiveOrderVo.setAmount5(wxOrder.getTotalPrice().toString());
                receiveOrderVo.setNumber9(wxUser.getPhone());
                receiveOrderVo.setThing3("购买会员");
                String s11 = DateUtils.parseDateToStr(DateUtils.YYYY_MM_DD_HH_MM_SS3, new Date());
                receiveOrderVo.setTime4(s11);
                String openid11 = "oHnzZ6HemJ3VIiEC4bj8FOj85-kM";//廖春香
                //gzhPushMessageService.SendWxMsg(openid11, receiveOrderVo);
            }


            //wxUser.setVipLevel(myCyhVip.getLevel());
            Date expireTime = wxUser.getExpireTime();
            Date date = null;
            if (Objects.isNull(expireTime)) {
                date = DateUtils.addYears(new Date(), 1);

            } else {
                if (expireTime.before(new Date())) {
                    //过期
                    date = DateUtils.addYears(new Date(), 1);
                } else {
                    //没过期
                    date = DateUtils.addYears(expireTime, 1);
                }
            }
            wxUser.setExpireTime(date);
            wxUser.setVipLevel(Integer.valueOf(remark));
            wxUserService.updateWxUser(wxUser);

            //上级的佣金
            synchronized (this) {
                Integer introMid = wxUser.getIntroMid();
                if (introMid != null && introMid > 0) {
                    WxUser wxUser1 = wxUserService.selectWxUserById(introMid);
                    if (wxUser1 == null) return;
                    Integer goldCoin = wxUser1.getGoldCoin();
                    BigDecimal totalPrice = wxOrder.getTotalPrice();

                    // 推荐人是股东 股东直推会员
                    if (wxUser1.getStockHolder() != null && wxUser1.getStockHolder().equals(1)) {
                        gudongjiangli(wxUser1,totalPrice,wxOrder,2);//2 直推会员

                        //添加股东推荐会员数量
                        MyCyhHolderVipNum myCyhHolderVipNum = new MyCyhHolderVipNum();
                        myCyhHolderVipNum.setCreated(new Date());
                        myCyhHolderVipNum.setUserId(wxUser1.getMid());
                        myCyhHolderVipNum.setToUserId(wxOrder.getUserId());
                        myCyhHolderVipNum.setVipLevel(Integer.valueOf(remark));

                        myCyhHolderVipNumService.insertMyCyhHolderVipNum(myCyhHolderVipNum);
                    } else if (wxUser1.getPartnerVip()!=null && wxUser1.getIsPartner().equals(1)    && wxUser1.getExpireTime2().after(new Date())){
                        // 推荐人是合伙人 [合伙人推荐会员]
                        if (wxUser1.getIsPartner() !=null && wxUser1.getPartnerVip()!=null && wxUser1.getIsPartner().equals(1) && wxUser1.getExpireTime2().after(new Date())) {
                            MyCyhPartner myCyhPartner1  = myCyhPartnerService.selectMyCyhPartnerById(wxUser1.getPartnerVip());

                            Boolean man = true;
                            if (myCyhPartner1 != null) {

                                //查看有没有特殊配置的合伙人推荐会员
                                Integer num= 0;
                                MyCyhParNowNum myCyhParNowNum = myCyhParNowNumService.selectByUserId(wxUser1.getMid());
                                if (myCyhParNowNum !=null){
                                    num =   myCyhParNowNum.getNum();

                                    MyCyhPartnerVipNum myCyhPartnerVipNum1 = new MyCyhPartnerVipNum();
                                    //myCyhPartnerVipNum.setPartnerId(partnerVip);
                                    myCyhPartnerVipNum1.setUserId(wxUser1.getMid());
                                    myCyhPartnerVipNum1.setVipLevel(1);//默认普通会员 才计算名额
                                    //自己已经推荐的
                                    Integer  num1 = myCyhPartnerVipNumService.selectMyCyhPartnerVipNumList(myCyhPartnerVipNum1).size();
                                    if (num1 >= num){
                                        man = true;
                                    }else {
                                        man = false;
                                    }

                                }else {
                                    //MyCyhPartner myCyhPartner1 = myCyhPartners.get(0);
                                    //查看推荐人分享购买的会员数量  从最先第一个会员开始
                                    //Integer partnerVip = wxUser1.getPartnerVip();
                                    MyCyhPartnerVipNum myCyhPartnerVipNum1 = new MyCyhPartnerVipNum();
                                    //myCyhPartnerVipNum.setPartnerId(partnerVip);
                                    myCyhPartnerVipNum1.setUserId(wxUser1.getMid());
                                    myCyhPartnerVipNum1.setVipLevel(1);//默认普通会员 才计算名额
                                    num = myCyhPartnerVipNumService.selectMyCyhPartnerVipNumList(myCyhPartnerVipNum1).size();
                                    //自己推荐的大于系统的默认值
                                    if (num >= myCyhPartner1.getOneNumber()){
                                        man = true;
                                    }else {
                                        man  =false;
                                    }
                                }


                                //直推金额
                                Integer amount = 0;

                                if (Integer.valueOf(remark) >1){
                                    BigDecimal highVip = myCyhPartner1.getHighVip();
                                    amount = totalPrice.multiply(highVip).divide(new BigDecimal(100)).intValue();
                                    man = false;//没满就不给股东分钱
                                }else {

                                    if (man){
                                        //满次后
                                        amount = totalPrice.multiply(myCyhPartner1.getFullFixedAmount()).divide(new BigDecimal(100)).intValue();

                                    }else {
                                        //没满
                                        amount = myCyhPartner1.getFixedAmount();

                                    }

                                }

                                if (amount > 0) {
                                    Integer goldCoin1 = amount + goldCoin;
                                    wxUser1.setGoldCoin(goldCoin1);
                                    wxUserService.updateWxUser(wxUser1);
                                    MyCyhPartnerVipNum myCyhPartnerVipNum =new MyCyhPartnerVipNum();
                                    //还需要添加一个数量
                                    myCyhPartnerVipNum.setCreated(new Date());
                                    myCyhPartnerVipNum.setToUserId(wxOrder.getUserId());
                                    myCyhPartnerVipNum.setUserId(wxUser1.getMid());//分享用户
                                    myCyhPartnerVipNum.setVipLevel(Integer.valueOf(remark));
                                    myCyhPartnerVipNum.setPartnerId(wxUser1.getPartnerVip());//合伙人等级等级
                                    myCyhPartnerVipNumService.insertMyCyhPartnerVipNum(myCyhPartnerVipNum);

                                    //金币日志
                                    UserGoldLog userGoldLog = new UserGoldLog();
                                    userGoldLog.setOldBalance(new BigDecimal(goldCoin));
                                    userGoldLog.setChangeBalance(new BigDecimal(amount));
                                    userGoldLog.setNewBalance(new BigDecimal(goldCoin1));
                                    userGoldLog.setType(4);//购买会员
                                    userGoldLog.setCreated(new Date());
                                    userGoldLog.setUserId(wxUser1.getMid());
                                    userGoldLog.setRemark("分享购买会员,推荐人[合伙人]获得佣金id:"+wxOrder.getUserId());//活动id
                                    userGoldLog.setFromSourceId(wxOrder.getUserId() + "");//购买人
                                    userGoldLogService.insertUserGoldLog(userGoldLog);

                                    if (System.getProperty("os.name")!= null && !System.getProperty("os.name").toLowerCase().startsWith("windows")){
                                        // 金币到账提醒
                                        if (StringUtils.isNotEmpty(wxUser1.getTsOpenid()) && wxUser1.getStatus() == 1) {
                                            ReceiveOrderVo1 receiveOrderVo1 = new ReceiveOrderVo1();
                                            receiveOrderVo1.setAmount1(amount.toString());
                                            receiveOrderVo1.setThing11("分享购买会员,推荐人[合伙人]获得佣金");
                                            Date date1 = new Date();
                                            String s = DateUtils.parseDateToStr(DateUtils.YYYY_MM_DD_HH_MM_SS3, date1);
                                            receiveOrderVo1.setTime3(s);
                                            String openid = wxUser1.getTsOpenid();
                                            //gzhPushMessageService.SendWxMsg1(openid, receiveOrderVo1);
                                        }
                                    }
                                }


                                //满了就是百分比 可以给股东线分团队奖励
                                if (man){
                                    Integer line = wxUser1.getLine();
                                    if (line !=null && line >0){
                                        WxUser wxUser2 = wxUserService.selectWxUserById(line);
                                        if (wxUser2 !=null && wxUser2.getStockHolder() !=null && wxUser2.getStockHolder().equals(1)){
                                            gudongjiangli(wxUser2,totalPrice,wxOrder,1);//股东团队奖励
                                        }
                                    }
                                }
                            }
                        }


                    }else if (wxUser1.getPromoDor() !=null && wxUser1.getPromoDor().equals(1) && wxUser1.getPromoLevel() !=null && wxUser1.getExpireTime1().after(new Date())){
                        MyCyhPromotionDor myCyhPromotionDor = myCyhPromotionDorService.selectMyCyhPromotionDorById(wxUser1.getPromoLevel());

                        Boolean man = true;
                        if (myCyhPromotionDor !=null){
                            //查看有没有特殊配置的推荐官推会员
                            Integer num= 0;
                            MyCyhProNowNum myCyhProNowNum = myCyhProNowNumService.selectByUserId(wxUser1.getMid());
                            if (myCyhProNowNum !=null){

                                num =  myCyhProNowNum.getNum();
                                MyCyhProVipNum myCyhProVipNum = new MyCyhProVipNum();
                                //myCyhPartnerVipNum.setPartnerId(partnerVip);
                                myCyhProVipNum.setUserId(wxUser1.getMid());
                                myCyhProVipNum.setVipLevel(1);//默认普通会员 才计算名额
                                //自己已经推荐的
                                Integer  num1 = myCyhProVipNumService.selectMyCyhProVipNumList(myCyhProVipNum).size();
                                if (num1 >= num){
                                    man = true;
                                }else {
                                    man = false;
                                }

                            }else {
                                MyCyhProVipNum myCyhProVipNum = new MyCyhProVipNum();
                                //myCyhPartnerVipNum.setPartnerId(partnerVip);
                                myCyhProVipNum.setUserId(wxUser1.getMid());
                                myCyhProVipNum.setVipLevel(1);//默认普通会员 才计算名额
                                //自己已经推荐的
                                Integer  num1 = myCyhProVipNumService.selectMyCyhProVipNumList(myCyhProVipNum).size();
                                //自己推荐的大于系统的默认值
                                if (num1 >= myCyhPromotionDor.getOneNumber()){
                                    man = true;
                                }else {
                                    man  =false;
                                }

                            }
                        }

                        //直推金额
                        Integer amount = 0;
                        if (Integer.valueOf(remark) >1){
                            BigDecimal highVip = myCyhPromotionDor.getHighVip();
                            amount = totalPrice.multiply(highVip).divide(new BigDecimal(100)).intValue();
                            man = false;//没满就不给股东分钱
                        }else {

                            if (man){
                                //满次后
                                amount = totalPrice.multiply(myCyhPromotionDor.getFullFixedAmount()).divide(new BigDecimal(100)).intValue();

                            }else {
                                //没满
                                amount = myCyhPromotionDor.getDirectVip().intValue();

                            }

                        }

                        Integer goldCoin2 = wxUser1.getGoldCoin();
                        if (amount > 0) {
                            Integer goldCoin1 = amount + goldCoin2;
                            wxUser1.setGoldCoin(goldCoin1);
                            wxUserService.updateWxUser(wxUser1);
                            MyCyhProVipNum myCyhProVipNum = new MyCyhProVipNum();
                            //还需要添加一个数量
                            myCyhProVipNum.setCreated(new Date());
                            myCyhProVipNum.setToUserId(wxOrder.getUserId());
                            myCyhProVipNum.setUserId(wxUser1.getMid());//分享用户
                            myCyhProVipNum.setVipLevel(Integer.valueOf(remark));
                            myCyhProVipNum.setPromoteId(wxUser1.getPromoLevel());
                            myCyhProVipNumService.insertMyCyhProVipNum(myCyhProVipNum);

                            //金币日志
                            UserGoldLog userGoldLog = new UserGoldLog();
                            userGoldLog.setOldBalance(new BigDecimal(goldCoin2));
                            userGoldLog.setChangeBalance(new BigDecimal(amount));
                            userGoldLog.setNewBalance(new BigDecimal(goldCoin1));
                            userGoldLog.setType(4);////购买会员
                            userGoldLog.setCreated(new Date());
                            userGoldLog.setUserId(wxUser1.getMid());
                            userGoldLog.setRemark("分享购买会员,推荐人[推荐官]获得佣金id:"+wxOrder.getUserId());//活动id
                            userGoldLog.setFromSourceId(wxOrder.getUserId() + "");//购买人
                            userGoldLogService.insertUserGoldLog(userGoldLog);

                            if (System.getProperty("os.name")!= null && !System.getProperty("os.name").toLowerCase().startsWith("windows")){
                                // 金币到账提醒
                                if (StringUtils.isNotEmpty(wxUser1.getTsOpenid()) && wxUser1.getStatus() == 1) {
                                    ReceiveOrderVo1 receiveOrderVo1 = new ReceiveOrderVo1();
                                    receiveOrderVo1.setAmount1(amount.toString());
                                    receiveOrderVo1.setThing11("分享购买会员,推荐人[推荐官]获得佣金");
                                    Date date1 = new Date();
                                    String s = DateUtils.parseDateToStr(DateUtils.YYYY_MM_DD_HH_MM_SS3, date1);
                                    receiveOrderVo1.setTime3(s);
                                    String openid = wxUser1.getTsOpenid();
                                    //gzhPushMessageService.SendWxMsg1(openid, receiveOrderVo1);
                                }
                            }

                        }
                        if (man){
                            //满了给合伙人  股东   分团队奖励
                            //合伙人分团队奖励
                            Integer lineTwo = wxUser1.getLineTwo();
                            if (lineTwo !=null && lineTwo >0 ){
                                WxUser wxUser2 = wxUserService.selectWxUserById(lineTwo);
                                if (wxUser2 != null && wxUser2.getIsPartner().equals(1) && wxUser2.getPartnerVip() != null) {
                                    hehuorenjiangli(wxUser2,totalPrice,wxOrder,1);//1 合伙人团队奖励

                                }
                            }

                            //股东分团队奖励
                            Integer line1 = wxUser1.getLine();
                            WxUser wxUser5 = wxUserService.selectWxUserById(line1);
                            if (wxUser5 != null && wxUser5.getStockHolder()!=null &&wxUser5.getStockHolder().equals(1) ) {
                                gudongjiangli(wxUser5,totalPrice,wxOrder,1);//1股东团队奖励

                            }
                        }


                    }else if (!Objects.isNull(wxUser1.getVipLevel()) && wxUser1.getExpireTime().after(new Date())) {
                        //最后走会员  会员推荐是会员
                        //会员奖励
                        huiyuanjiangli(wxUser1,totalPrice,wxOrder,1);//"分享购买会员,会员获得奖励";

                        //wxUser1的 股东团队奖励
                        Integer line1 = wxUser1.getLine();
                        WxUser wxUser5 = wxUserService.selectWxUserById(line1);
                        if (wxUser5 != null && wxUser5.getStockHolder()!=null &&wxUser5.getStockHolder().equals(1) ) {
                            gudongjiangli(wxUser5,totalPrice,wxOrder,1);//1 分享购买会员 股东团队奖励
                        }

                        //wxUser1的合伙人团队奖励
                        Integer line = wxUser1.getLineTwo();
                        WxUser wxUser4 = wxUserService.selectWxUserById(line);
                        if (wxUser4 != null && wxUser4.getIsPartner().equals(1) && wxUser4.getPartnerVip() != null) {
                            hehuorenjiangli(wxUser4,totalPrice,wxOrder,1);//1 分享购买会员 合伙人团队奖励

                        }

                        //wxUser1 推荐官 拿团队奖励
                        Integer lineThree = wxUser1.getLineThree();
                        WxUser wxUser6 = wxUserService.selectWxUserById(lineThree);
                        if (wxUser6 !=null && wxUser6.getPromoLevel() !=null && wxUser6.getPromoDor().equals(1) && wxUser6.getExpireTime1().after(new Date())){
                            tuijianguanjiangli(wxUser6,totalPrice,wxOrder,1);//分享购买会员 推荐官团队奖励
                        }

                    }
                }
            }

            // 给群管理发佣金
           /* MyCarBook myCarBook = myCarBookService.selectMyCarBookByUserId(wxUser.getMid());
            if (myCarBook != null && StringUtils.isNotEmpty(myCarBook.getGroup()) && myCarBook.getPosition().equals("1000")) {
                MyCyhPosition myCyhPosition = new MyCyhPosition();
                myCyhPosition.setIsEnable(1);
                myCyhPosition.setIsGroupManager(1);
                myCyhPosition.setIsUp(1);
                List<MyCyhPosition> myCyhPositions = myCyhPositionService.selectMyCyhPositionList(myCyhPosition);
                System.out.println("长度" + myCyhPositions.size());
                for (MyCyhPosition cyhPosition : myCyhPositions) {
                    // 只有群主获得佣金
                    if (cyhPosition.getVipExtra() != null && (cyhPosition.getVipExtra() > 0) && cyhPosition.getId().equals(6)) {
                        MyCarBook myCarBook1 = new MyCarBook();
                        myCarBook1.setGroup(myCarBook.getGroup());
                        myCarBook1.setPosition(cyhPosition.getId() + "");
                        List<MyCarBook> myCarBooks = myCarBookService.selectMyCarBookList(myCarBook1);
                        if (myCarBooks.size() > 0) {
                            for (MyCarBook carBook : myCarBooks) {
                                WxUser wxUser1 = wxUserService.selectWxUserById(carBook.getUserId());
                                Integer goldCoin = wxUser1.getGoldCoin();
                                BigDecimal totalPrice = wxOrder.getTotalPrice();
                                //int now = totalPrice.multiply(cyhPosition.getActivityCommission()).divide(new BigDecimal(100)).intValue();
                                int now = cyhPosition.getVipExtra();
                                if (now > 0) {
                                    //金币日志
                                    UserGoldLog userGoldLog = new UserGoldLog();
                                    userGoldLog.setOldBalance(new BigDecimal(goldCoin));
                                    userGoldLog.setChangeBalance(new BigDecimal(now));
                                    userGoldLog.setNewBalance(new BigDecimal(goldCoin + now));
                                    userGoldLog.setType(4);//变动类型  4购买会员佣金
                                    userGoldLog.setCreated(new Date());
                                    userGoldLog.setUserId(wxUser1.getMid());
                                    userGoldLog.setRemark("群友购买会员,群主得佣金");//
                                    userGoldLog.setStatus(1);//可提现
                                    //userGoldLog.setSignId(myCyhActivitySign.getId());//报名的id
                                    userGoldLog.setFromSourceId(wxUser.getMid() + "");//那个用户购买

                                    userGoldLogService.insertUserGoldLog(userGoldLog);

                                    // 金币到账提醒
                                    if (StringUtils.isNotEmpty(wxUser1.getTsOpenid()) && wxUser1.getStatus() == 1) {
                                        ReceiveOrderVo1 receiveOrderVo1 = new ReceiveOrderVo1();
                                        receiveOrderVo1.setAmount1(String.valueOf(now));
                                        receiveOrderVo1.setThing11("群友购买会员,群管理得佣金");
                                        Date date1 = new Date();
                                        String s = DateUtils.parseDateToStr(DateUtils.YYYY_MM_DD_HH_MM_SS3, date1);
                                        receiveOrderVo1.setTime3(s);
                                        String openid = wxUser1.getTsOpenid();
                                        gzhPushMessageService.SendWxMsg1(openid, receiveOrderVo1);
                                    }
                                } else {
                                    log.error("用户" + wxUser1.getMid() + "获得的金币:" + totalPrice.multiply(cyhPosition.getActivityCommission()).divide(new BigDecimal(100)));
                                }
                            }
                        }
                    }
                }
            }*/

        } else if (wxOrder.getType().equals(5)) {
            //充值金币
            WxUser wxUser = wxUserService.selectWxUserById(wxOrder.getUserId());

            //发给管理员
            ReceiveOrderVo receiveOrderVo = new ReceiveOrderVo();
            receiveOrderVo.setAmount5(wxOrder.getTotalPrice().toString());
            receiveOrderVo.setNumber9(wxUser.getPhone());
            receiveOrderVo.setThing3("充值金币");
            String s11 = DateUtils.parseDateToStr(DateUtils.YYYY_MM_DD_HH_MM_SS3, new Date());
            receiveOrderVo.setTime4(s11);
            String openid11 = "oHnzZ6HemJ3VIiEC4bj8FOj85-kM";//廖春香
            //gzhPushMessageService.SendWxMsg(openid11, receiveOrderVo);

            Integer i = wxOrder.getTotalPrice().intValue();
            Integer goldCoin = wxUser.getGoldCoin();
            Integer nowGold = goldCoin + i;
            //金币日志
            UserGoldLog userGoldLog = new UserGoldLog();
            userGoldLog.setOldBalance(new BigDecimal(goldCoin));
            userGoldLog.setChangeBalance(new BigDecimal(i));
            userGoldLog.setNewBalance(new BigDecimal(nowGold));
            userGoldLog.setType(3);//充值金币
            userGoldLog.setCreated(new Date());
            userGoldLog.setUserId(wxOrder.getUserId());
            userGoldLog.setRemark("充值金币");//
            //userGoldLog.setFromSourceId(wxOrder.getUserId()+"");//购买人
            userGoldLogService.insertUserGoldLog(userGoldLog);
            wxUser.setGoldCoin(nowGold);
            wxUserService.updateWxUser(wxUser);
            wxOrder.setStatus(1);
            updateWxOrder(wxOrder);

        } else if (wxOrder.getType().equals(6)) {
            //团购商品
            wxOrder.setStatus(1);
            updateWxOrder(wxOrder);
            WxUser wxUser = wxUserService.selectWxUserById(wxOrder.getUserId());

            //发给管理员
            ReceiveOrderVo receiveOrderVo = new ReceiveOrderVo();
            receiveOrderVo.setAmount5(wxOrder.getTotalPrice().toString());
            receiveOrderVo.setNumber9(wxUser.getPhone());
            receiveOrderVo.setThing3("团购商品");
            String s11 = DateUtils.parseDateToStr(DateUtils.YYYY_MM_DD_HH_MM_SS3, new Date());
            receiveOrderVo.setTime4(s11);
            String openid11 = "oHnzZ6HemJ3VIiEC4bj8FOj85-kM";//廖春香
            //gzhPushMessageService.SendWxMsg(openid11, receiveOrderVo);


            //上级推荐用户的佣金
            synchronized (this) {
                MyCyhShopProduct myCyhShopProduct = myCyhShopProductService.selectMyCyhShopProductById(Integer.valueOf(wxOrder.getRemark()));

                if (myCyhShopProduct !=null){
                    MyProduct myProduct = new MyProduct();
                    myProduct.setCreated(new Date());
                    myProduct.setDesc(myCyhShopProduct.getDesc());
                    myProduct.setUserId(wxOrder.getUserId());
                    myProduct.setShopProductId(Integer.valueOf(wxOrder.getRemark()) );
                    myProduct.setName(myCyhShopProduct.getName());
                    myProduct.setOrderId(wxOrder.getId());
                    myProduct.setPrice(myCyhShopProduct.getPrice());
                    myProduct.setShopId(myCyhShopProduct.getShopId());
                    myProduct.setExpireTime(myCyhShopProduct.getEndTime());
                    myProduct.setImg(myCyhShopProduct.getImg());
                    myProductService.insertMyProduct(myProduct);

                    Integer number = myCyhShopProduct.getNumber();
                    number--;
                    myCyhShopProduct.setNumber(number);
                    myCyhShopProductService.updateMyCyhShopProduct(myCyhShopProduct);

                    //给商家分钱
                    Integer shopId = myCyhShopProduct.getShopId();
                    MyCyhShop myCyhShop = myCyhShopService.selectMyCyhShopById(shopId);
                    if (myCyhShop !=null){
                        Integer userId = myCyhShop.getUserId();
                        if (userId !=null){
                            WxUser wxUser1 = wxUserService.selectWxUserById(userId);
                            if (wxUser1!=null){
                                Integer goldCoin = wxUser1.getGoldCoin();
                                Integer totalPrice = wxOrder.getTotalPrice().intValue();
                                Integer total = goldCoin + totalPrice;
                                //金币日志
                                UserGoldLog userGoldLog = new UserGoldLog();
                                userGoldLog.setOldBalance(new BigDecimal(goldCoin));
                                userGoldLog.setChangeBalance(new BigDecimal(totalPrice));
                                userGoldLog.setNewBalance(new BigDecimal(total));
                                userGoldLog.setType(16);//团购商品商家入账
                                userGoldLog.setCreated(new Date());
                                userGoldLog.setUserId(userId);
                                userGoldLog.setRemark("客户购买团购商品,商家入账");//活动id
                                userGoldLog.setFromSourceId(wxOrder.getId());//订单id
                                userGoldLogService.insertUserGoldLog(userGoldLog);

                                wxUser1.setGoldCoin(total);
                                wxUserService.updateWxUser(wxUser1);
                            }
                        }
                    }
                }



                //Integer introMid = wxUser.getIntroMid();
                /*if (introMid != null && introMid > 0) {
                    WxUser wxUser1 = wxUserService.selectWxUserById(introMid);
                    // 有会员登记才能得佣金
                    if (wxUser1 != null && !Objects.isNull(wxUser1.getVipLevel()) && wxUser1.getExpireTime().after(new Date())) {
                        Integer goldCoin = wxUser1.getGoldCoin();
                        BigDecimal totalPrice = wxOrder.getTotalPrice();
                        MyCyhVip myCyhVip1 = myCyhVipService.selectMyCyhVipByLevel(wxUser1.getVipLevel());

                        if (myCyhVip1 != null) {
                            BigDecimal change = totalPrice.multiply(myCyhVip1.getCommission()).divide(new BigDecimal(100));
                            Integer total = goldCoin + change.intValue();
                            wxUser1.setGoldCoin(total);
                            wxUserService.updateWxUser(wxUser1);

                            //金币日志
                            UserGoldLog userGoldLog = new UserGoldLog();
                            userGoldLog.setOldBalance(new BigDecimal(goldCoin));
                            userGoldLog.setChangeBalance(new BigDecimal(change.intValue()));
                            userGoldLog.setNewBalance(new BigDecimal(total));
                            userGoldLog.setType(9);//购买团购商品佣金
                            userGoldLog.setCreated(new Date());
                            userGoldLog.setUserId(introMid);
                            userGoldLog.setRemark("下级购买团购商品,上级获得佣金");//活动id
                            userGoldLog.setFromSourceId(wxOrder.getUserId() + "");//购买人
                            userGoldLogService.insertUserGoldLog(userGoldLog);


                            // 金币到账提醒
                            if (StringUtils.isNotEmpty(wxUser1.getTsOpenid()) && wxUser1.getStatus() == 1) {
                                ReceiveOrderVo1 receiveOrderVo1 = new ReceiveOrderVo1();
                                receiveOrderVo1.setAmount1(change.toString());
                                receiveOrderVo1.setThing11("下级购买团购商品,上级获得佣金");
                                Date date1 = new Date();
                                String s = DateUtils.parseDateToStr(DateUtils.YYYY_MM_DD_HH_MM_SS3, date1);
                                receiveOrderVo1.setTime3(s);
                                String openid = wxUser1.getTsOpenid();
                                gzhPushMessageService.SendWxMsg1(openid, receiveOrderVo1);
                            }
                        }
                    }
                }*/
            }

            // 给群管理发佣金
            /*MyCarBook myCarBook = myCarBookService.selectMyCarBookByUserId(wxUser.getMid());
            if (myCarBook != null && StringUtils.isNotEmpty(myCarBook.getGroup()) && myCarBook.getPosition().equals("1000")) {
                MyCyhPosition myCyhPosition = new MyCyhPosition();
                myCyhPosition.setIsEnable(1);
                myCyhPosition.setIsGroupManager(1);
                myCyhPosition.setIsUp(1);
                List<MyCyhPosition> myCyhPositions = myCyhPositionService.selectMyCyhPositionList(myCyhPosition);
                System.out.println("长度" + myCyhPositions.size());
                for (MyCyhPosition cyhPosition : myCyhPositions) {
                    if (cyhPosition.getActivityCommission() != null) {
                        MyCarBook myCarBook1 = new MyCarBook();
                        myCarBook1.setGroup(myCarBook.getGroup());
                        myCarBook1.setPosition(cyhPosition.getId() + "");
                        List<MyCarBook> myCarBooks = myCarBookService.selectMyCarBookList(myCarBook1);
                        if (myCarBooks.size() > 0) {
                            for (MyCarBook carBook : myCarBooks) {
                                WxUser wxUser1 = wxUserService.selectWxUserById(carBook.getUserId());
                                Integer goldCoin = wxUser1.getGoldCoin();
                                BigDecimal totalPrice = wxOrder.getTotalPrice();
                                int now = totalPrice.multiply(cyhPosition.getActivityCommission()).divide(new BigDecimal(100)).intValue();
                                if (now > 0) {
                                    //金币日志
                                    UserGoldLog userGoldLog = new UserGoldLog();
                                    userGoldLog.setOldBalance(new BigDecimal(goldCoin));
                                    userGoldLog.setChangeBalance(new BigDecimal(now));
                                    userGoldLog.setNewBalance(new BigDecimal(goldCoin + now));
                                    userGoldLog.setType(9);//变动类型  9购买团购商品佣金
                                    userGoldLog.setCreated(new Date());
                                    userGoldLog.setUserId(wxUser1.getMid());
                                    userGoldLog.setRemark("群友购买团购商品,群管理得佣金");//
                                    userGoldLog.setStatus(1);//可提现
                                    //userGoldLog.setSignId(myCyhActivitySign.getId());//报名的id
                                    userGoldLog.setFromSourceId(wxUser.getMid() + "");//那个用户购买

                                    userGoldLogService.insertUserGoldLog(userGoldLog);

                                    // 金币到账提醒
                                    if (StringUtils.isNotEmpty(wxUser1.getTsOpenid()) && wxUser1.getStatus() == 1) {
                                        ReceiveOrderVo1 receiveOrderVo1 = new ReceiveOrderVo1();
                                        receiveOrderVo1.setAmount1(String.valueOf(now));
                                        receiveOrderVo1.setThing11("群友购买团购商品,群管理得佣金");
                                        Date date1 = new Date();
                                        String s = DateUtils.parseDateToStr(DateUtils.YYYY_MM_DD_HH_MM_SS3, date1);
                                        receiveOrderVo1.setTime3(s);
                                        String openid = wxUser1.getTsOpenid();
                                        gzhPushMessageService.SendWxMsg1(openid, receiveOrderVo1);
                                    }
                                } else {
                                    log.error("用户" + wxUser1.getMid() + "获得的金币:" + totalPrice.multiply(cyhPosition.getActivityCommission()).divide(new BigDecimal(100)));
                                }
                            }
                        }
                    }
                }
            }*/

        } else if (wxOrder.getType().equals(7)) {

            WxUser wxUser = wxUserService.selectWxUserById(wxOrder.getUserId());
            // 优惠券
            wxOrder.setStatus(1);
            updateWxOrder(wxOrder);

            //发给管理员
            ReceiveOrderVo receiveOrderVo = new ReceiveOrderVo();
            receiveOrderVo.setAmount5(wxOrder.getTotalPrice().toString());
            receiveOrderVo.setNumber9(wxUser.getPhone());
            receiveOrderVo.setThing3("购买优惠券");
            String s11 = DateUtils.parseDateToStr(DateUtils.YYYY_MM_DD_HH_MM_SS3, new Date());
            receiveOrderVo.setTime4(s11);
            String openid11 = "oHnzZ6HemJ3VIiEC4bj8FOj85-kM";//廖春香
            //gzhPushMessageService.SendWxMsg(openid11, receiveOrderVo);





            //上级推荐用户的佣金
            synchronized (this) {
                MyCyhShopCoupon myCyhShopCoupon = myCyhShopCouponService.selectMyCyhShopCouponById(Integer.valueOf(wxOrder.getRemark()));
                if (myCyhShopCoupon !=null){
                    MyCoupon myCoupon = new MyCoupon();
                    myCoupon.setIsCheck(0);
                    myCoupon.setUserId(wxOrder.getUserId());
                    myCoupon.setShopId(myCyhShopCoupon.getShopId());
                    myCoupon.setExpireTime(myCyhShopCoupon.getEndTime());
                    myCoupon.setShopCouponId(myCyhShopCoupon.getId());
                    myCoupon.setCreated(new Date());
                    myCoupon.setTitle(myCyhShopCoupon.getTitle());
                    myCoupon.setPrice(myCyhShopCoupon.getPrice());
                    myCoupon.setDesc(myCyhShopCoupon.getDesc());
                    myCoupon.setOrderId(wxOrder.getId());
                    myCouponService.insertMyCoupon(myCoupon);

                    Integer number = myCyhShopCoupon.getNumber();
                    number--;
                    myCyhShopCoupon.setNumber(number);
                    myCyhShopCouponService.updateMyCyhShopCoupon(myCyhShopCoupon);

                    //给商家分钱
                    Integer shopId = myCyhShopCoupon.getShopId();
                    MyCyhShop myCyhShop = myCyhShopService.selectMyCyhShopById(shopId);
                    if (myCyhShop !=null){
                        Integer userId = myCyhShop.getUserId();
                        if (userId !=null){
                            WxUser wxUser1 = wxUserService.selectWxUserById(userId);
                            if (wxUser1!=null){
                                Integer goldCoin = wxUser1.getGoldCoin();
                                Integer totalPrice = wxOrder.getTotalPrice().intValue();
                                Integer total = goldCoin + totalPrice;
                                //金币日志
                                UserGoldLog userGoldLog = new UserGoldLog();
                                userGoldLog.setOldBalance(new BigDecimal(goldCoin));
                                userGoldLog.setChangeBalance(new BigDecimal(totalPrice));
                                userGoldLog.setNewBalance(new BigDecimal(total));
                                userGoldLog.setType(17);//优惠券 商家入账
                                userGoldLog.setCreated(new Date());
                                userGoldLog.setUserId(userId);
                                userGoldLog.setRemark("客户优惠券,商家入账");//活动id
                                userGoldLog.setFromSourceId(wxOrder.getId());//订单id
                                userGoldLogService.insertUserGoldLog(userGoldLog);

                                wxUser1.setGoldCoin(total);
                                wxUserService.updateWxUser(wxUser1);
                            }
                        }
                    }

                }




                //Integer introMid = wxUser.getIntroMid();
                /*if (introMid != null && introMid > 0) {
                    WxUser wxUser1 = wxUserService.selectWxUserById(introMid);
                    // 有会员登记才能得佣金
                    if (wxUser1 != null && !Objects.isNull(wxUser1.getVipLevel()) && wxUser1.getExpireTime().after(new Date())) {
                        Integer goldCoin = wxUser1.getGoldCoin();
                        BigDecimal totalPrice = wxOrder.getTotalPrice();
                        MyCyhVip myCyhVip1 = myCyhVipService.selectMyCyhVipByLevel(wxUser1.getVipLevel());

                        if (myCyhVip1 != null) {
                            BigDecimal change = totalPrice.multiply(myCyhVip1.getCommission()).divide(new BigDecimal(100));
                            Integer total = goldCoin + change.intValue();
                            wxUser1.setGoldCoin(total);
                            wxUserService.updateWxUser(wxUser1);

                            //金币日志
                            UserGoldLog userGoldLog = new UserGoldLog();
                            userGoldLog.setOldBalance(new BigDecimal(goldCoin));
                            userGoldLog.setChangeBalance(new BigDecimal(change.intValue()));
                            userGoldLog.setNewBalance(new BigDecimal(total));
                            userGoldLog.setType(10);//购买商家优惠券
                            userGoldLog.setCreated(new Date());
                            userGoldLog.setUserId(introMid);
                            userGoldLog.setRemark("下级购买商家优惠券,上级获得佣金");
                            userGoldLog.setFromSourceId(wxOrder.getUserId() + "");//购买人
                            userGoldLogService.insertUserGoldLog(userGoldLog);


                            // 金币到账提醒
                            if (StringUtils.isNotEmpty(wxUser1.getTsOpenid()) && wxUser1.getStatus() == 1) {
                                ReceiveOrderVo1 receiveOrderVo1 = new ReceiveOrderVo1();
                                receiveOrderVo1.setAmount1(change.toString());
                                receiveOrderVo1.setThing11("下级购买商家优惠券,上级获得佣金");
                                Date date1 = new Date();
                                String s = DateUtils.parseDateToStr(DateUtils.YYYY_MM_DD_HH_MM_SS3, date1);
                                receiveOrderVo1.setTime3(s);
                                String openid = wxUser1.getTsOpenid();
                                gzhPushMessageService.SendWxMsg1(openid, receiveOrderVo1);
                            }
                        }
                    }
                }*/
            }

            // 给群管理发佣金
            /*MyCarBook myCarBook = myCarBookService.selectMyCarBookByUserId(wxUser.getMid());
            if (myCarBook != null && StringUtils.isNotEmpty(myCarBook.getGroup()) && myCarBook.getPosition().equals("1000")) {
                MyCyhPosition myCyhPosition = new MyCyhPosition();
                myCyhPosition.setIsEnable(1);
                myCyhPosition.setIsGroupManager(1);
                myCyhPosition.setIsUp(1);
                List<MyCyhPosition> myCyhPositions = myCyhPositionService.selectMyCyhPositionList(myCyhPosition);
                System.out.println("长度" + myCyhPositions.size());
                for (MyCyhPosition cyhPosition : myCyhPositions) {
                    if (cyhPosition.getActivityCommission() != null) {
                        MyCarBook myCarBook1 = new MyCarBook();
                        myCarBook1.setGroup(myCarBook.getGroup());
                        myCarBook1.setPosition(cyhPosition.getId() + "");
                        List<MyCarBook> myCarBooks = myCarBookService.selectMyCarBookList(myCarBook1);
                        if (myCarBooks.size() > 0) {
                            for (MyCarBook carBook : myCarBooks) {
                                WxUser wxUser1 = wxUserService.selectWxUserById(carBook.getUserId());
                                Integer goldCoin = wxUser1.getGoldCoin();
                                BigDecimal totalPrice = wxOrder.getTotalPrice();
                                int now = totalPrice.multiply(cyhPosition.getActivityCommission()).divide(new BigDecimal(100)).intValue();
                                if (now > 0) {
                                    //金币日志
                                    UserGoldLog userGoldLog = new UserGoldLog();
                                    userGoldLog.setOldBalance(new BigDecimal(goldCoin));
                                    userGoldLog.setChangeBalance(new BigDecimal(now));
                                    userGoldLog.setNewBalance(new BigDecimal(goldCoin + now));
                                    userGoldLog.setType(10);//  10购买优惠券
                                    userGoldLog.setCreated(new Date());
                                    userGoldLog.setUserId(wxUser1.getMid());
                                    userGoldLog.setRemark("群友购买商家优惠券,群管理得佣金");//
                                    userGoldLog.setStatus(1);//可提现
                                    //userGoldLog.setSignId(myCyhActivitySign.getId());//报名的id
                                    userGoldLog.setFromSourceId(wxUser.getMid() + "");//那个用户购买

                                    userGoldLogService.insertUserGoldLog(userGoldLog);

                                    // 金币到账提醒
                                    if (StringUtils.isNotEmpty(wxUser1.getTsOpenid()) && wxUser1.getStatus() == 1) {
                                        ReceiveOrderVo1 receiveOrderVo1 = new ReceiveOrderVo1();
                                        receiveOrderVo1.setAmount1(String.valueOf(now));
                                        receiveOrderVo1.setThing11("群友购买商家优惠券,群管理得佣金");
                                        Date date1 = new Date();
                                        String s = DateUtils.parseDateToStr(DateUtils.YYYY_MM_DD_HH_MM_SS3, date1);
                                        receiveOrderVo1.setTime3(s);
                                        String openid = wxUser1.getTsOpenid();
                                        gzhPushMessageService.SendWxMsg1(openid, receiveOrderVo1);
                                    }
                                } else {
                                    log.error("用户" + wxUser1.getMid() + "获得的金币:" + totalPrice.multiply(cyhPosition.getActivityCommission()).divide(new BigDecimal(100)));
                                }
                            }
                        }
                    }
                }
            }*/


        } else if (wxOrder.getType().equals(8)) {
            //购买商城商品
            String remark = wxOrder.getRemark(); // 关联到 my_goods_buy
            MyGoodsBuy myGoodsBuy = myGoodsBuyService.selectMyGoodsBuyById(Integer.valueOf(remark));
            if (myGoodsBuy != null) {
                synchronized (this) {
                    myGoodsBuy.setIsPay(1);
                    myGoodsBuyService.updateMyGoodsBuy(myGoodsBuy);

                    Integer goodsId = myGoodsBuy.getGoodsId();
                    MyGoods myGoods = myGoodsService.selectMyGoodsById(goodsId);
                    Integer freezeStock = myGoods.getFreezeStock();
                    Integer stock = myGoods.getStock();
                    if (freezeStock == null) {
                        freezeStock = 0;
                    }
                    // 这里最好使用乐观锁
                    freezeStock++;
                    myGoods.setFreezeStock(freezeStock);
                    stock--;
                    myGoods.setStock(stock);
                    myGoodsService.updateMyGoods(myGoods);

                    if (stock > 0) {
                        MyGoods cacheObject = redisCache.getCacheObject("goods:" + goodsId);
                        if (cacheObject != null) {
                            //下了单没付款的情况,缓存中减少了,实际的库存没变 刷新缓存
                            if (!cacheObject.getStock().equals(stock)) {
                                cacheObject.setStock(stock);

                                long l = DateUtil.timeSub12(myGoods.getEndTime(), new Date());
                                l = l + 3600L; // 结束时间加一个小时过期
                                redisCache.setCacheObject("goods:" + goodsId, myGoods, Integer.valueOf(l + ""), TimeUnit.SECONDS);

                            }
                        }
                    }
                }
            }

        } else if (wxOrder.getType().equals(9)) {
            //购买头衔
            String remark = wxOrder.getRemark();
            MyFiles myFiles = myFilesService.selectMyFilesById(Integer.valueOf(remark));
            if (myFiles != null) {
                myFiles.setIsPay(1);
                myFilesService.updateMyFiles(myFiles);

                //头衔更新 在my_car_book.position


            }

        } else if (wxOrder.getType().equals(10)) {
            //购买推荐官
            wxOrder.setStatus(1);
            updateWxOrder(wxOrder);
            String remark = wxOrder.getRemark();
            Integer userId = wxOrder.getUserId();
            BigDecimal totalPrice1 = wxOrder.getTotalPrice();
            WxUser wxUser = wxUserService.selectWxUserById(userId);
            if (wxUser != null) {
                //wxUser.setPromoDor(Integer.valueOf(remark));
                Date expireTime1 = wxUser.getExpireTime1();
                Date date = null;
                if (Objects.isNull(expireTime1)) {
                    date = DateUtils.addYears(new Date(), 1);

                } else {
                    if (expireTime1.before(new Date())) {
                        //过期
                        date = DateUtils.addYears(new Date(), 1);
                    } else {
                        //没过期
                        date = DateUtils.addYears(expireTime1, 1);
                    }
                }

                Integer lineThree = wxUser.getLineThree();
                if (lineThree !=null && lineThree >0){
                    WxUser wxUser1 = wxUserService.selectWxUserById(lineThree);
                    if (wxUser1 !=null){
                        MyCyhGladTiding myCyhGladTiding = new MyCyhGladTiding();
                        myCyhGladTiding.setUserId(lineThree);
                        myCyhGladTiding.setCreated(new Date());
                        myCyhGladTiding.setInfo("团队成员升级啦id:"+userId);
                        myCyhGladTidingService.insertMyCyhGladTiding(myCyhGladTiding);
                    }
                }
                Integer lineTwo = wxUser.getLineTwo();
                if (lineTwo !=null && lineTwo >0){
                    WxUser wxUser1 = wxUserService.selectWxUserById(lineTwo);
                    if (wxUser1 !=null){
                        MyCyhGladTiding myCyhGladTiding = new MyCyhGladTiding();
                        myCyhGladTiding.setUserId(lineThree);
                        myCyhGladTiding.setCreated(new Date());
                        myCyhGladTiding.setInfo("团队成员升级啦id:"+userId);
                        myCyhGladTidingService.insertMyCyhGladTiding(myCyhGladTiding);
                    }
                }

                //wxUser.setPartnerVip(Integer.valueOf(remark));
                wxUser.setExpireTime1(date);
                wxUser.setLineThree(userId);// 推广大使自己
                wxUser.setPromoLevel(Integer.valueOf(remark));
                wxUser.setPromoDor(1);
                wxUserService.updateWxUser(wxUser);

                //发给管理员
                ReceiveOrderVo receiveOrderVo = new ReceiveOrderVo();
                receiveOrderVo.setAmount5(wxOrder.getTotalPrice().toString());
                receiveOrderVo.setNumber9(wxUser.getPhone());
                receiveOrderVo.setThing3("购买推荐管");
                String s11 = DateUtils.parseDateToStr(DateUtils.YYYY_MM_DD_HH_MM_SS3, new Date());
                receiveOrderVo.setTime4(s11);
                String openid11 = "oHnzZ6HemJ3VIiEC4bj8FOj85-kM";//廖春香
                //gzhPushMessageService.SendWxMsg(openid11, receiveOrderVo);

            }

            //上级的佣金
            synchronized (this) {
                Integer introMid = wxUser.getIntroMid();
                if (introMid != null && introMid > 0) {
                    WxUser wxUser1 = wxUserService.selectWxUserById(introMid);
                    // 是股东
                    if (wxUser1.getStockHolder()!=null && wxUser1.getStockHolder().equals(1) ){
                        gudongjiangli(wxUser1,totalPrice1,wxOrder,3);//3 直推推荐官

                    }else if (wxUser1.getIsPartner().equals(1) && wxUser1.getExpireTime2().after(new Date())){
                        //不是股东 // 推荐人是合伙人 [合伙人推荐推荐官]
                        Integer goldCoin = wxUser1.getGoldCoin();

                        MyCyhPartner myCyhPartner = myCyhPartnerService.selectMyCyhPartnerById(wxUser1.getPartnerVip());
                        if (myCyhPartner != null && myCyhPartner.getIsEnable().equals(1)) {
                            Integer amount = totalPrice1.multiply(myCyhPartner.getOnePromo()).divide(new BigDecimal(100)).intValue();
                            if (amount > 0) {
                                Integer goldCoin1 = amount + goldCoin;
                                wxUser1.setGoldCoin(goldCoin1);
                                wxUserService.updateWxUser(wxUser1);

                                //金币日志
                                UserGoldLog userGoldLog = new UserGoldLog();
                                userGoldLog.setOldBalance(new BigDecimal(goldCoin));
                                userGoldLog.setChangeBalance(new BigDecimal(amount));
                                userGoldLog.setNewBalance(new BigDecimal(goldCoin1));
                                userGoldLog.setType(11);//购买推广大使
                                userGoldLog.setCreated(new Date());
                                userGoldLog.setUserId(wxUser1.getMid());
                                userGoldLog.setRemark("分享购买推荐官,推荐人[合伙人]获得佣金"+"[id:"+wxOrder.getUserId()+"]");//活动id
                                userGoldLog.setFromSourceId(wxOrder.getUserId() + "");//购买人
                                userGoldLogService.insertUserGoldLog(userGoldLog);


                                if (System.getProperty("os.name")!= null && !System.getProperty("os.name").toLowerCase().startsWith("windows")){
                                    // 金币到账提醒
                                    if (StringUtils.isNotEmpty(wxUser1.getTsOpenid()) && wxUser1.getStatus() == 1) {
                                        ReceiveOrderVo1 receiveOrderVo1 = new ReceiveOrderVo1();
                                        receiveOrderVo1.setAmount1(amount.toString());
                                        receiveOrderVo1.setThing11("分享购买推广大使,推荐人[合伙人]获得佣金"+"[id:"+wxOrder.getUserId()+"]");
                                        Date date1 = new Date();
                                        String s = DateUtils.parseDateToStr(DateUtils.YYYY_MM_DD_HH_MM_SS3, date1);
                                        receiveOrderVo1.setTime3(s);
                                        String openid = wxUser1.getTsOpenid();
                                        //gzhPushMessageService.SendWxMsg1(openid, receiveOrderVo1);
                                    }
                                }

                            }
                        }

                        //股东线 团队奖励
                        Integer line = wxUser1.getLine();
                        WxUser wxUser2 = wxUserService.selectWxUserById(line);
                        if (wxUser2 != null && wxUser2.getStockHolder() !=null ){
                            gudongjiangli(wxUser2,totalPrice1,wxOrder,1);//1股东团队奖励
                        }


                    }else if (wxUser1.getPromoDor() !=null && wxUser1.getPromoLevel() !=null &&  wxUser1.getPromoDor().equals(1) && wxUser1.getExpireTime1().after(new Date())){
                        //推荐人是推广大使
                        Integer goldCoin = wxUser1.getGoldCoin();
                        MyCyhPromotionDor myCyhPromotionDor = myCyhPromotionDorService.selectMyCyhPromotionDorById(wxUser1.getPromoLevel());
                        if (myCyhPromotionDor != null && myCyhPromotionDor.getIsEnable().equals(1)) {
                            Integer amount = totalPrice1.multiply(myCyhPromotionDor.getDirectThrust()).divide(new BigDecimal(100)).intValue();
                            if (amount > 0) {
                                Integer goldCoin1 = amount + goldCoin;
                                wxUser1.setGoldCoin(goldCoin1);
                                wxUserService.updateWxUser(wxUser1);

                                //金币日志
                                UserGoldLog userGoldLog = new UserGoldLog();
                                userGoldLog.setOldBalance(new BigDecimal(goldCoin));
                                userGoldLog.setChangeBalance(new BigDecimal(amount));
                                userGoldLog.setNewBalance(new BigDecimal(goldCoin1));
                                userGoldLog.setType(10);//购买推广大使
                                userGoldLog.setCreated(new Date());
                                userGoldLog.setUserId(wxUser1.getMid());
                                userGoldLog.setRemark("分享购买推荐官,推荐人[推荐官]获得佣金"+"[id:"+wxOrder.getUserId()+"]");//活动id
                                userGoldLog.setFromSourceId(wxOrder.getUserId() + "");//购买人
                                userGoldLogService.insertUserGoldLog(userGoldLog);

                                //flag = true;
                                if (System.getProperty("os.name")!= null && !System.getProperty("os.name").toLowerCase().startsWith("windows")){
                                    // 金币到账提醒
                                    if (StringUtils.isNotEmpty(wxUser1.getTsOpenid()) && wxUser1.getStatus() == 1) {
                                        ReceiveOrderVo1 receiveOrderVo1 = new ReceiveOrderVo1();
                                        receiveOrderVo1.setAmount1(amount.toString());
                                        receiveOrderVo1.setThing11("分享购买推荐官,推荐人[推荐官]获得佣金"+"[id:"+wxOrder.getUserId()+"]");
                                        Date date1 = new Date();
                                        String s = DateUtils.parseDateToStr(DateUtils.YYYY_MM_DD_HH_MM_SS3, date1);
                                        receiveOrderVo1.setTime3(s);
                                        String openid = wxUser1.getTsOpenid();
                                        //gzhPushMessageService.SendWxMsg1(openid, receiveOrderVo1);
                                    }
                                }

                            }
                        }

                        //todo  推荐人的上级是合伙人 给合伙人分团队奖励
                        Integer lineTwo = wxUser1.getLineTwo();
                        if (lineTwo != null && lineTwo > 0) {
                            WxUser wxUser2 = wxUserService.selectWxUserById(lineTwo);
                            if (wxUser2.getIsPartner().equals(1) && wxUser2.getPartnerVip() != null && wxUser2.getExpireTime2().after(new Date())) {
                                hehuorenjiangli(wxUser2,totalPrice1,wxOrder,1);
                            }
                        }

                        //推荐人的上级是合伙人 合伙人上级股东线
                        Integer line = wxUser1.getLine();
                        if (line != null && line > 0) {
                            WxUser wxUser2 = wxUserService.selectWxUserById(line);
                            if (wxUser2.getStockHolder() != null && wxUser2.getStockHolder().equals(1)) {
                                gudongjiangli(wxUser2,totalPrice1,wxOrder,1);//1股东团队奖励
                            }
                        }
                    }

                }
            }


        } else if (wxOrder.getType().equals(11)) {
            //购买合伙人
            wxOrder.setStatus(1);
            updateWxOrder(wxOrder);
            String remark = wxOrder.getRemark();
            Integer userId = wxOrder.getUserId();
            WxUser wxUser = wxUserService.selectWxUserById(userId);
            if (wxUser != null) {
                wxUser.setIsPartner(1);
                Date expireTime2 = wxUser.getExpireTime2();
                Date date = null;
                if (Objects.isNull(expireTime2)) {
                    date = DateUtils.addYears(new Date(), 99);

                } else {
                    if (expireTime2.before(new Date())) {
                        //过期
                        date = DateUtils.addYears(new Date(), 99);
                    } else {
                        //没过期
                        date = DateUtils.addYears(expireTime2, 99);
                    }
                }
                wxUser.setExpireTime2(date);
                wxUser.setIsPartner(1);
                wxUser.setPartnerVip(Integer.valueOf(remark));
                wxUser.setLineTwo(userId);//合伙人的分销级别
                wxUserService.updateWxUser(wxUser);

                //发给管理员
                ReceiveOrderVo receiveOrderVo = new ReceiveOrderVo();
                receiveOrderVo.setAmount5(wxOrder.getTotalPrice().toString());
                receiveOrderVo.setNumber9(wxUser.getPhone());
                receiveOrderVo.setThing3("购买合伙人");
                String s11 = DateUtils.parseDateToStr(DateUtils.YYYY_MM_DD_HH_MM_SS3, new Date());
                receiveOrderVo.setTime4(s11);
                String openid11 = "oHnzZ6HemJ3VIiEC4bj8FOj85-kM";//廖春香
                //gzhPushMessageService.SendWxMsg(openid11, receiveOrderVo);
            }

            //上级的佣金
            synchronized (this) {
                BigDecimal totalPrice1 = wxOrder.getTotalPrice();
                Integer introMid = wxUser.getIntroMid();
                if (introMid != null && introMid > 0) {
                    // 推荐人
                    WxUser wxUser1 = wxUserService.selectWxUserById(introMid);
                    BigDecimal totalPrice = wxOrder.getTotalPrice();
                    //推荐人是股东
                    if (wxUser1.getStockHolder() !=null && wxUser1.getStockHolder().equals(1)){
                        //股东推荐购买合伙人
                        gudongjiangli(wxUser1,totalPrice1,wxOrder,4);//4股东推荐购买合伙人

                    }else if (wxUser1.getIsPartner().equals(1) && wxUser1.getExpireTime2().after(new Date())){
                        //wxUser1为合伙人推荐购买合伙人
                        hehuorenjiangli(wxUser1,totalPrice,wxOrder,2);//合伙人推荐合伙人
                        //wxUser1的股东线 团队奖励
                        Integer line = wxUser1.getLine();
                        if (line !=null && line >0){
                            WxUser wxUser2 = wxUserService.selectWxUserById(line);
                            if (wxUser2 !=null && wxUser2.getStockHolder() !=null && wxUser2.getStockHolder().equals(1)){
                                gudongjiangli(wxUser2,totalPrice1,wxOrder,1); //1团队奖励
                            }
                        }
                    }
                }
            }

        }else if (wxOrder.getType().equals(12)){
            //购买店铺
            MyCyhShopCattle myCyhShopCattle = myCyhShopCattleService.selectMyCyhShopCattleById(Integer.valueOf(wxOrder.getRemark()));
            if (myCyhShopCattle !=null){
                myCyhShopCattle.setPay(1);
                Date expireTime = myCyhShopCattle.getEndTime();
                Date date = null;
                if (Objects.isNull(expireTime)) {
                    date = DateUtils.addYears(new Date(), 1);

                } else {
                    if (expireTime.before(new Date())) {
                        //过期
                        date = DateUtils.addYears(new Date(), 1);
                    } else {
                        //没过期
                        date = DateUtils.addYears(expireTime, 1);
                    }
                }
                myCyhShopCattle.setEndTime(date);
                myCyhShopCattleService.updateMyCyhShopCattle(myCyhShopCattle);

                wxOrder.setStatus(1);
                updateWxOrder(wxOrder);



                //上级的佣金
                synchronized (this) {
                    Integer userId = wxOrder.getUserId();
                    WxUser wxUser = wxUserService.selectWxUserById(userId);
                    wxUser.setIsMerchant(1);
                    wxUserService.updateWxUser(wxUser);
                    if (System.getProperty("os.name")!= null && !System.getProperty("os.name").toLowerCase().startsWith("windows")){
                        //发给管理员
                        ReceiveOrderVo receiveOrderVo = new ReceiveOrderVo();
                        receiveOrderVo.setAmount5(wxOrder.getTotalPrice().toString());
                        receiveOrderVo.setNumber9(wxUser.getPhone());
                        receiveOrderVo.setThing3("商家入驻");
                        String s11 = DateUtils.parseDateToStr(DateUtils.YYYY_MM_DD_HH_MM_SS3, new Date());
                        receiveOrderVo.setTime4(s11);
                        String openid11 = "oHnzZ6HemJ3VIiEC4bj8FOj85-kM";//廖春香
                        //gzhPushMessageService.SendWxMsg(openid11, receiveOrderVo);
                    }


                    Integer introMid = wxUser.getIntroMid();
                    if (introMid !=null && introMid >0){
                        WxUser wxUser1 = wxUserService.selectWxUserById(introMid);
                        if (wxUser1 !=null){

                            BigDecimal totalPrice = wxOrder.getTotalPrice();

                            //是股东
                            if (wxUser1.getStockHolder() != null && wxUser1.getStockHolder().equals(1)) {

                                MyCyhHolder myCyhHolder = myCyhHolderService.selectMyCyhHolderById(1);
                                if (myCyhHolder != null) {
                                    //股东直推商家
                                    gudongjiangli(wxUser1,totalPrice,wxOrder,6);//分享购买商家会员,股东获得奖励
                                }

                            } else  if (wxUser1.getIsPartner() !=null && wxUser1.getPartnerVip()!=null &&
                                wxUser1.getIsPartner().equals(1) && wxUser1.getExpireTime2() !=null  &&
                                wxUser1.getExpireTime2().after(new Date())) {
                                //合伙人直推商家会员
                                hehuorenjiangli(wxUser1,totalPrice,wxOrder,6);//分享购买商家会员,合伙人获得奖励

                                //找合伙人的上级股东分团队奖励
                                if (wxUser1.getLine() !=null && wxUser1.getLine() >0){
                                    WxUser wxUser2 = wxUserService.selectWxUserById(wxUser1.getLine());
                                    if (wxUser2 !=null && wxUser2.getStockHolder() !=null && wxUser2.getStockHolder().equals(1)){
                                        gudongjiangli(wxUser2,totalPrice,wxOrder,5);//分享购买商家会员,股东获得团队奖励
                                    }
                                }



                            }else if (wxUser1.getPromoDor() !=null && wxUser1.getPromoDor().equals(1) &&
                                wxUser1.getPromoLevel()!=null && wxUser1.getExpireTime1()!=null && wxUser1.getExpireTime1().after(new Date())){
                                //推荐官直推商家会员
                                tuijianguanjiangli(wxUser1,totalPrice,wxOrder,3);//分享购买商家会员,推荐官获得奖励


                                if (wxUser1.getLineTwo() !=null && wxUser1.getLineTwo() >0){
                                    WxUser wxUser2 = wxUserService.selectWxUserById(wxUser1.getLineTwo());
                                    if (wxUser2 !=null && wxUser2.getIsPartner() !=null && wxUser2.getIsPartner().equals(1)
                                        && wxUser2.getExpireTime2() !=null && wxUser2.getExpireTime2().after(new Date()) ){
                                        //合伙人获得团队奖励
                                        hehuorenjiangli(wxUser2,totalPrice,wxOrder,5);//分享购买商家会员,合伙人获得团队奖励
                                    }
                                }
                                if (wxUser1.getLine() !=null && wxUser1.getLine() >0){
                                    WxUser wxUser2 = wxUserService.selectWxUserById(wxUser1.getLine());
                                    if (wxUser2 !=null && wxUser2.getStockHolder() !=null && wxUser2.getStockHolder().equals(1) ){
                                        //股东获得团队奖励
                                        gudongjiangli(wxUser2,totalPrice,wxOrder,5);//分享购买商家会员,股东获得团队奖励
                                    }
                                }



                            }else if (!Objects.isNull(wxUser1.getVipLevel()) && wxUser1.getExpireTime() !=null &&
                                //会员分享商家会员
                                wxUser1.getExpireTime().after(new Date())) {
                                huiyuanjiangli(wxUser1,totalPrice,wxOrder,2);//分享购买商家会员,会员获得奖励



                                //推荐官分团队奖励
                                if (wxUser1.getLineThree() !=null && wxUser1.getLineThree()>0){
                                    WxUser wxUser2 = wxUserService.selectWxUserById(wxUser1.getLineThree());
                                    if  (wxUser2 !=null && wxUser2.getPromoDor() !=null && wxUser2.getPromoDor().equals(1)
                                        && wxUser2.getExpireTime1() !=null && wxUser2.getExpireTime1().after(new Date()) ){
                                        tuijianguanjiangli(wxUser,totalPrice,wxOrder,2);//分享购买商家会员,推荐官获得团队奖励
                                    }

                                }

                                //合伙人获得团队奖励
                                if (wxUser1.getLineTwo() !=null && wxUser1.getLineTwo() >0){
                                    WxUser wxUser2 = wxUserService.selectWxUserById(wxUser1.getLineTwo());
                                    if (wxUser2 !=null && wxUser2.getIsPartner() !=null && wxUser2.getIsPartner().equals(1)
                                        && wxUser2.getExpireTime2() !=null && wxUser2.getExpireTime2().after(new Date()) ){
                                        hehuorenjiangli(wxUser2,totalPrice,wxOrder,5);//分享购买商家会员,合伙人获得团队奖励
                                    }
                                }

                                //股东获得团队奖励
                                if (wxUser1.getLine() !=null && wxUser1.getLine() >0){
                                    WxUser wxUser2 = wxUserService.selectWxUserById(wxUser1.getLine());
                                    if (wxUser2 !=null && wxUser2.getStockHolder() !=null && wxUser2.getStockHolder().equals(1) ){

                                        gudongjiangli(wxUser2,totalPrice,wxOrder,5);//分享购买商家会员,股东获得团队奖励
                                    }
                                }

                            }

                        }
                    }

                }
            }


        }

    }

    @Override
    public WxOrder selectWxOrderByOrderNo(String officeId) {
        return wxOrderMapper.selectWxOrderByOrderNo(officeId);
    }

    @Override
    public void refund111(WxOrder wxOrder) {
        MyCyhActivity myCyhActivity = myCyhActivityService.selectMyCyhActivityById(Integer.valueOf(wxOrder.getRemark()));
        if (myCyhActivity !=null && !myCyhActivity.getCate().equals("3")){
            if (new Date().after(myCyhActivity.getAtimeStart())){

                throw new CustomException("活动已开始暂不退款");
            }else {

                MyWxPayConfigUtil myWxPayConfigUtil = new MyWxPayConfigUtil();
                myWxPayConfigUtil.setDate(new Date());
                myWxPayConfigUtil.setOrderNo(wxOrder.getOrderNo());
                myWxPayConfigUtil.setOrderId(wxOrder.getId());
                myWxPayConfigUtil.setTotalAmount(wxOrder.getTotalPrice().multiply(new BigDecimal(100)).toString());
                Map<String, String> map = PayUtil.test5(myWxPayConfigUtil);
                //  退款map:{logNo=202404104236647013, mercId=800551000056528, amount=1, tradeNo=1777994133571371008, subject=, goodsTag=, message=交易退款成功, signValue=fb4d0994e271a7c418ccf58f438c6304, result=S, returnCode=000000, total_amount=1, selOrderNo=, sysTime=20240410173848, attach=, txnAmt=1}
                String returnCode = map.get("returnCode");
                if (!returnCode.equals("000000")){
                    throw new CustomException(map.get("message"));
                }



                //关联到活动保名的id
                String transactionId = wxOrder.getTransactionId();
                if (StringUtils.isNotEmpty(transactionId)){
                    MyCyhActivitySign myCyhActivitySign = myCyhActivitySignService.selectMyCyhActivitySignById(Integer.valueOf(transactionId));
                    if (myCyhActivitySign !=null){
                        if (myCyhActivitySign.getIsPay().equals(1)){

                            //更新报名的人
                            Integer leave = myCyhActivity.getLeave();
                            Integer nums = myCyhActivitySign.getNums();
                            leave -= nums;
                            myCyhActivity.setLeave(leave);
                            myCyhActivityService.updateMyCyhActivity(myCyhActivity);

                            myCyhActivitySign.setIsPay(2);//已退款
                            int i = myCyhActivitySignService.updateMyCyhActivitySign(myCyhActivitySign);
                            System.out.println("报名标记:"+i);

                            wxOrder.setStatus(2);
                            wxOrderMapper.updateWxOrder(wxOrder);
                            System.out.println("订单标记:"+i);


                            Integer ticketId = myCyhActivitySign.getTicketId();
                            if (!Objects.isNull(ticketId)){
                                MyCyhTicket myCyhTicket = myCyhTicketService.selectMyCyhTicketById(ticketId);
                                if (  myCyhTicket != null){

                                    Integer numbers = myCyhTicket.getNumbers();
                                    Integer nums1 = myCyhActivitySign.getNums();
                                    numbers -=nums1;
                                    myCyhTicket.setNumbers(numbers);
                                    myCyhTicketService.updateMyCyhTicket(myCyhTicket);
                                }


                            }

                            UserGoldLog userGoldLog =new UserGoldLog();
                            userGoldLog.setSignId(myCyhActivitySign.getId());
                            UserGoldLog goldLog = userGoldLogService.selectUserGoldLogBySign(myCyhActivitySign.getId());
                            if (goldLog !=null){
                                goldLog.setStatus(3);//返回到系统
                                userGoldLogService.updateUserGoldLog(goldLog);
                            }

                        }
                    }
                }


            }


        }
    }


}
